Created
February 23, 2015 10:36
-
-
Save nubbel/877fed31d1034489633e to your computer and use it in GitHub Desktop.
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 ViewModel | |
class Attribute | |
attr_reader :name | |
attr_accessor :model_value, :view_value | |
def initialize(name, model_value = :_undefined, view_value = :_undefined) | |
@name = name | |
@model_value = model_value | |
@view_value = view_value | |
end | |
def has_model_value? | |
@model_value != :_undefined | |
end | |
def has_view_value? | |
@view_value != :_undefined | |
end | |
end | |
attr_reader :attributes | |
def initialize(options = {}) | |
@attributes = HashWithIndifferentAccess.new | |
self.model_attributes = options[:model_attributes] if options[:model_attributes] | |
self.view_attributes = options[:view_attributes] if options[:view_attributes] | |
end | |
def model_attributes=(attrs) | |
attrs.each do |name, value| | |
(@attributes[name] ||= Attribute.new(name)).model_value = value | |
end | |
end | |
def model_attributes | |
map_hash_values(@attributes) { |name| model_value(name) } | |
end | |
def view_attributes=(attrs) | |
attrs.each do |name, value| | |
(@attributes[name] ||= Attribute.new(name)).view_value = value | |
end | |
end | |
def view_attributes | |
map_hash_values(@attributes) { |name| view_value(name) } | |
end | |
def model_value(name) | |
attr = @attributes.fetch(name) | |
attr.has_model_value? ? attr.model_value : transform_view_value(name, attr.view_value) | |
end | |
def view_value(name) | |
attr = @attributes.fetch(name) | |
attr.has_view_value? ? attr.view_value : transform_model_value(name, attr.model_value) | |
end | |
# override points | |
def transform_model_value(name, model_value) | |
model_value | |
end | |
def transform_view_value(name, view_value) | |
view_value | |
end | |
private | |
def map_hash_values(hash) | |
hash.inject(HashWithIndifferentAccess.new) do |ret, (k, v)| | |
ret.update k => yield(k, v) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment