Skip to content

Instantly share code, notes, and snippets.

@mattetti
Last active December 16, 2015 10:59
Show Gist options
  • Save mattetti/5424282 to your computer and use it in GitHub Desktop.
Save mattetti/5424282 to your computer and use it in GitHub Desktop.
o_O
module Views
class Rat < SimpleDelegator
begin
include Decorator
rescue NameError => e
end
def initialize(data)
super OpenStruct.new(attributes[data])
end
def attributes
->(data) {
rat_keys = %w|id previous_id created_at current|
foo_keys = %w|fish_foos badger_foos|
result = data.select &keys(*rat_keys)
widgets = data['metadata']['baz'].select &keys(*foo_keys)
result['widgets'] = []
widgets.inject(result['widgets'], &transform_foo)
result
}
end
def fish_foos
widgets(:fish).foo
end
def widgets(type=:all)
widgets = super().map &Widget
return widgets if type == :all
widgets.find { |c| c == type }
end
def keys(*keys)
->(k,v) { keys.include? k }
end
def badger_foos
widget(:badger).foos
end
def persisted?
self['id']
end
def transform_foo
->(foo) { foo.select &keys(*%w|id name type|) }
end
def transform_foos
->(result,(type,data)) {
map = { 'fish_foos' => 'Fish Foos', 'badger_foos' => 'Badger Foos' }
type = map[type]
foos = data['foos'].map &transform_foo
result.push('type' => type, 'foos' => foos)
}
end
class Widget < OpenStruct
def self.to_proc
proc(&method(:new))
end
def ==(other)
{ fish: 'Fish Foos', badger: 'Badger Foos' }[other] == type
end
def foos
self['foos'].map &Foo
end
def to_partial_path
'rats/widget'
end
def type
self['type']
end
end
class Foo < OpenStruct
def self.to_proc
proc(&method(:new))
end
def name
self['name']
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment