Created
November 27, 2015 11:57
-
-
Save alfonsojimenez/b70daed84eca77a26f31 to your computer and use it in GitHub Desktop.
XgStruct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class XgStruct | |
def initialize(attributes) | |
@attributes = process(attributes) | |
end | |
def method_missing(name, *args, &block) | |
if (name =~ /^(\w+)=$/) == 0 | |
@attributes[$1.to_sym] = args[0] | |
else | |
@attributes[name] || super | |
end | |
end | |
private | |
def process(attributes) | |
attributes.each do |key, value| | |
attributes[key] = self.class.new(value) if value.is_a?(Hash) | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe XgStruct do | |
subject { XgStruct.new(foo: :bar, one: { two: :three }) } | |
describe '#foo' do | |
it 'returns bar' do | |
expect(subject.foo).to eq(:bar) | |
end | |
end | |
describe '#foo=' do | |
before { subject.foo = :baz } | |
it 'returns baz' do | |
expect(subject.foo).to eq(:baz) | |
end | |
end | |
describe '#one#two' do | |
subject { XgStruct.new(one: { two: :three }) } | |
it 'returns three' do | |
expect(subject.one.two).to eq(:three) | |
end | |
end | |
describe '#one#two#three' do | |
subject { XgStruct.new(one: { two: {three: :four}}) } | |
it 'returns four' do | |
expect(subject.one.two.three).to eq(:four) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment