Created
March 16, 2011 22:13
-
-
Save dkubb/873428 to your computer and use it in GitHub Desktop.
Poor-man's Embedded Value
This file contains 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 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