Skip to content

Instantly share code, notes, and snippets.

@alfonsojimenez
Created November 27, 2015 11:57
Show Gist options
  • Save alfonsojimenez/b70daed84eca77a26f31 to your computer and use it in GitHub Desktop.
Save alfonsojimenez/b70daed84eca77a26f31 to your computer and use it in GitHub Desktop.
XgStruct
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
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