Sha256: ed7146a9eadb74a80802a89b5977ba91a918b8ac594084a845234385ec668874

Contents?: true

Size: 1.66 KB

Versions: 3

Compression:

Stored size: 1.66 KB

Contents

require 'representable/hash'
require 'representable/decorator'

module Reform
  class Representer < Representable::Decorator
    # Invokes #to_hash and/or #from_hash with #options. This provides a hook for other
    # modules to add options for the representational process.
    module WithOptions
      class Options < Hash
        def include!(names)
          self[:include] ||= []
          self[:include] += names
          self
        end

        def exclude!(names)
          self[:exclude] ||= []
          self[:exclude] +=  names
          self
        end
      end

      def options
        Options.new
      end

      def to_hash(*)
        super(options)
      end

      def from_hash(*)
        super(options)
      end
    end

    include Representable::Hash

    # Returns hash of all property names.
    def fields
      representable_attrs.map(&:name)
    end

    def nested_forms(&block)
      clone_config!.
        find_all { |attr| attr.options[:form] }.
        collect  { |attr| [attr, represented.send(attr.getter)] }. # DISCUSS: can't we do this with the Binding itself?
        each(&block)
    end

  private
    def clone_config!
      # TODO: representable_attrs.clone! which does exactly what's done below.
      attrs = Representable::Config.new
      attrs.inherit(representable_attrs) # since in every use case we modify Config we clone.
      @representable_attrs = attrs
    end

    def self.inline_representer(base_module, &block) # DISCUSS: separate module?
      Class.new(Form) do
        instance_exec &block

        def self.name # FIXME: needed by ActiveModel::Validation - why?
          "AnonInlineForm"
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
reform-0.2.3 lib/reform/representer.rb
reform-0.2.2 lib/reform/representer.rb
reform-0.2.1 lib/reform/representer.rb