Skip to content

Commit

Permalink
Hashie::Trash transforms can be inherited.
Browse files Browse the repository at this point in the history
  • Loading branch information
FoboCasteR authored and dblock committed Aug 11, 2014
1 parent 0c3dd5a commit 7df81b6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

* [#183](https://github.com/intridea/hashie/pull/183): Added Mash#load with YAML file support - [@gregory](https://github.com/gregory).
* [#197](https://github.com/intridea/hashie/pull/197): Dont convert keys to string on initalization of mash - [@gregory](https://github.com/gregory).
* [#201](https://github.com/intridea/hashie/pull/201): Hashie::Trash transforms can be inherited - [@fobocaster](https://github.com/fobocaster).
* Your contribution here.

## 3.2.0 (7/10/2014)
Expand Down
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

0 comments on commit 7df81b6

Please sign in to comment.