|
| 1 | +module MountainView |
| 2 | + class Presenter |
| 3 | + class_attribute :_properties, instance_accessor: false |
| 4 | + self._properties = {} |
| 5 | + |
| 6 | + attr_reader :slug, :properties |
| 7 | + |
| 8 | + def initialize(slug, properties = {}) |
| 9 | + @slug = slug |
| 10 | + @properties = default_properties.deep_merge(properties) |
| 11 | + end |
| 12 | + |
| 13 | + def render(context) |
| 14 | + context.extend ViewContext |
| 15 | + context.inject_component_context self |
| 16 | + context.render partial: partial |
| 17 | + end |
| 18 | + |
| 19 | + def partial |
| 20 | + "#{slug}/#{slug}" |
| 21 | + end |
| 22 | + |
| 23 | + private |
| 24 | + |
| 25 | + def default_properties |
| 26 | + self.class._properties.inject({}) do |sum, (k, v)| |
| 27 | + sum[k] = v[:default] |
| 28 | + sum |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + class << self |
| 33 | + def component_for(*args) |
| 34 | + klass = "#{args.first.to_s.camelize}Component".safe_constantize |
| 35 | + klass ||= self |
| 36 | + klass.new(*args) |
| 37 | + end |
| 38 | + |
| 39 | + def properties(*args) |
| 40 | + opts = args.extract_options! |
| 41 | + properties = args.inject({}) do |sum, name| |
| 42 | + sum[name] = opts |
| 43 | + sum |
| 44 | + end |
| 45 | + define_property_methods(args) |
| 46 | + self._properties = _properties.merge(properties) |
| 47 | + end |
| 48 | + alias_method :property, :properties |
| 49 | + |
| 50 | + private |
| 51 | + |
| 52 | + def define_property_methods(names = []) |
| 53 | + names.each do |name| |
| 54 | + next if method_defined?(name) |
| 55 | + define_method name do |
| 56 | + properties[name.to_sym] |
| 57 | + end |
| 58 | + end |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + module ViewContext |
| 63 | + attr_reader :_component |
| 64 | + delegate :properties, to: :_component |
| 65 | + |
| 66 | + def inject_component_context(component) |
| 67 | + @_component = component |
| 68 | + protected_methods = MountainView::Presenter.public_methods(false) |
| 69 | + methods = component.public_methods(false) - protected_methods |
| 70 | + methods.each do |meth| |
| 71 | + next if self.class.method_defined?(meth) |
| 72 | + self.class.delegate meth, to: :_component |
| 73 | + end |
| 74 | + end |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments