Sha256: 9fe0db0211b0d36aa1a2a740c52f500c407d1f82fbb11805414a93060af886b2

Contents?: true

Size: 1.98 KB

Versions: 2

Compression:

Stored size: 1.98 KB

Contents

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

module Reform
  class Representer < Representable::Decorator
    include Representable::Hash::AllowSymbols

    extend Uber::InheritableAttr
    inheritable_attr :options # FIXME: this doesn't need to be inheritable.
    # self.options = {}


    class Options < ::Hash
      def include!(names)
        includes.push(*names) #if names.size > 0
        self
      end

      def exclude!(names)
        excludes.push(*names) #if names.size > 0
        self
      end

      def excludes
        self[:exclude] ||= []
      end

      def includes
        self[:include] ||= []
      end
    end


    include Representable::Hash

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

    def nested_forms(&block)
      clone_config!.
        find_all { |attr| attr[:form] }.
        each(&block)
    end

    def self.for(options)
      clone.tap do |representer|
        representer.options = options
      end
    end

    def self.default_inline_class
      options[:form_class]
    end

    def self.clone # called in inheritable_attr :representer_class.
      Class.new(self) # By subclassing, representable_attrs.clone is called.
    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

    # Inline forms always get saved in :extend.
    def self.build_inline(base, features, name, options, &block)
      name = name.to_s.singularize.camelize

      features = options[:features]

      Class.new(base || default_inline_class) do
        include *features

        class_eval &block

        @form_name = name

        def self.name # needed by ActiveModel::Validation and I18N.
          @form_name
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
reform-1.2.0.beta2 lib/reform/representer.rb
reform-1.2.0.beta1 lib/reform/representer.rb