Skip to content

Instantly share code, notes, and snippets.

@TeWu
Forked from dkubb/ev.rb
Created August 2, 2011 23:47
Show Gist options
  • Save TeWu/1121533 to your computer and use it in GitHub Desktop.
Save TeWu/1121533 to your computer and use it in GitHub Desktop.
Poor-man's Embedded Value
class User
include DataMapper::Resource
property :id, Serial
property :username, String, :required => true, :unique => true
property :address_street_address, String
property :address_location, String
property :address_subdivision, String
property :address_country, String
def address
@address ||= Address.new(self, 'address')
end
def address=(new_address)
new_address.each { |key, value| address[key] = value }
end
end
class Address
def initialize(resource, prefix)
@resource = resource
@prefix = prefix
end
def [](key)
send(key)
end
def []=(key, value)
send("#{key}=", value)
end
def respond_to?(method, include_private = false)
@resource.respond_to?(proxy_method_for(method)) || super
end
def method_missing(method, *args, &block)
if respond_to?(method)
@resource.send(proxy_method_for(method), *args, &block)
else
super
end
end
private
def proxy_method_for(method)
"#{@prefix}_#{method}"
end
end
__END__
# the above will allow code like the following to work as expected:
user = User.create(
:username => 'dkubb',
:address => {
:location => 'Mission',
:subdivision => 'BC',
:country => 'Canada',
}
)
puts user.address.location # => "Mission"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment