Sha256: e10987359e1b981e874acd2f23883c88d9e4287bd494b926714acfdf49ba12c0

Contents?: true

Size: 1.49 KB

Versions: 11

Compression:

Stored size: 1.49 KB

Contents

module Faceted

  module Model

    require 'json'
    require 'active_support/core_ext/hash'

    # Class methods ============================================================

    module ModelClassMethods

      def build_association_from(field)
        bare_name = field.gsub(/_id$/, '')
        if field =~ /_id$/
          klass = eval "#{scope}#{bare_name.classify}"
          fields << bare_name.to_sym
          define_method :"#{bare_name}" do
            klass.new(:id => self.send(field))
          end
        end
      end

      def create(params={})
        obj = self.new(params)
        obj.save
        obj
      end

      def field(name, args={})
        fields << name
        define_method :"#{name}" do
          val = instance_variable_get("@#{name}")
          val.nil? ? args[:default] : val
        end
        unless args[:read_only]
          define_method :"#{name}=" do |val|
            instance_variable_set("@#{name}", val)
          end
        end
        build_association_from(name.to_s) if name.to_s.include?("id") && ! args[:skip_association]
      end

      def fields
        @fields ||= [:id, :excludes]
      end

      def materialize(objects=[])
        objects.compact.inject([]) do |a, object|
          interface = self.new
          interface.send(:object=, object)
          interface.send(:initialize_with_object)
          a << interface
        end
      end

      def scope
        parent.to_s == "Object" ? "::" : "#{parent.to_s}::"
      end

    end

  end

end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
faceted-1.3.3 lib/faceted/model.rb
faceted-1.3.2 lib/faceted/model.rb
faceted-1.3.1 lib/faceted/model.rb
faceted-1.3.0 lib/faceted/model.rb
faceted-1.2.3 lib/faceted/model.rb
faceted-1.2.2 lib/faceted/model.rb
faceted-1.2.1 lib/faceted/model.rb
faceted-1.2.0 lib/faceted/model.rb
faceted-1.1.1 lib/faceted/model.rb
faceted-1.1.0 lib/faceted/model.rb
faceted-1.0.8 lib/faceted/model.rb