Sha256: 19d7fb8d19429f392a77de66f80beed6e1398d80f14a28ee7096fe87e74f3ca8

Contents?: true

Size: 1.71 KB

Versions: 4

Compression:

Stored size: 1.71 KB

Contents

module PushType
  class RelationField < PushType::FieldType

    options template: 'relation'

    def initialize(*args)
      super
      raise ArgumentError, "Relation field names must end with suffix `_id` or `_ids`." unless relation_name
    end

    def json_primitive
       multiple? ? :array : super 
    end

    def label
      super || relation_name.humanize
    end

    def html_options
      super.merge(multiple: multiple?)
    end

    def choices
      if relation_root.respond_to?(:hash_tree)
        flatten_tree(relation_root.hash_tree)
      else
        relation_root.all.map { |item| item_hash(item) }
      end
    end

    def relation_name
      @relation_name ||= (rel = name.to_s.gsub!(/_ids?$/, '')) && (rel && multiple? ? rel.pluralize : rel)
    end

    def relation_class
      (@opts[:to] || relation_name.singularize).to_s.classify.constantize
    end

    def relation_root
      relation_class
    end

    private

    def defaults
      super.merge({
        label:    nil,
        mapping:  { value: :id, text: :title }
      })
    end

    def item_hash(item, d = 0)
      {
        value:  item.send(@opts[:mapping][:value]),
        text:   item.send(@opts[:mapping][:text]),
        depth:  d
      }
    end

    def flatten_tree(hash_tree, d = 0)
      hash_tree.flat_map do |parent, children|
        [
          item_hash(parent, d),
          flatten_tree(children, d+1)
        ]
      end.flatten
    end

    on_instance do |object, field|
      object.class_eval do
        define_method(field.relation_name.to_sym) do
          field.relation_class.find field.json_value unless field.json_value.blank?
        end unless method_defined?(field.relation_name.to_sym)
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
push_type_core-0.6.0 app/fields/push_type/relation_field.rb
push_type_core-0.6.0.beta.4 app/fields/push_type/relation_field.rb
push_type_core-0.6.0.beta.3 app/fields/push_type/relation_field.rb
push_type_core-0.6.0.beta.2 app/fields/push_type/relation_field.rb