Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inheritable Trash tranforms #201

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 10 additions & 8 deletions lib/hashie/trash.rb
Expand Up @@ -39,6 +39,16 @@ def self.property(property_name, options = {})
end
end

class << self
attr_reader :transforms
end
instance_variable_set('@transforms', {})

def self.inherited(klass)
super
klass.instance_variable_set('@transforms', transforms.dup)
end

# Set a value on the Dash in a Hash-like way. Only works
# on pre-existing properties.
def []=(property, value)
Expand Down Expand Up @@ -69,10 +79,6 @@ def self.permitted_input_keys

private

def self.properties
@properties ||= []
end

def self.translations
@translations ||= {}
end
Expand All @@ -81,10 +87,6 @@ def self.inverse_translations
@inverse_translations ||= Hash[translations.map(&:reverse)]
end

def self.transforms
@transforms ||= {}
end

# Raises an NoMethodError if the property doesn't exist
#
def property_exists?(property)
Expand Down
22 changes: 22 additions & 0 deletions spec/hashie/trash_spec.rb
Expand Up @@ -186,6 +186,28 @@ class TrashLambdaTest3 < Hashie::Trash
end
end

describe 'inheritable transforms' do
class TrashA < Hashie::Trash
property :some_value, transform_with: lambda { |v| v.to_i }
end

class TrashB < TrashA
property :some_other_value, transform_with: lambda { |v| v.to_i }
end

class TrashC < TrashB
property :some_value, transform_with: lambda { |v| -v.to_i }
end

it 'inherit properties transforms' do
expect(TrashB.new(some_value: '123', some_other_value: '456').some_value).to eq(123)
end

it 'replaces property transform' do
expect(TrashC.new(some_value: '123', some_other_value: '456').some_value).to eq(-123)
end
end

it 'raises an error when :from have the same value as property' do
expect do
class WrongTrash < Hashie::Trash
Expand Down