Module: MetaField::ModelExtension::ClassMethods

Defined in:
lib/meta_field/extension.rb

Instance Method Summary collapse

Instance Method Details

#metaObject

meta_join でメタ属性での絞り込みを行う際にArelっぽく標記するために使うProxyを得る メタ属性は単純なカラム名で扱うことができないため、Proxyを通して操作する

Book.meta_join(:subtitle: Book.meta[:subtitle].matches_any(['%KEYWORD1%', '%KEYWORD2%']))
# => SELECT "books".*
#    FROM "books" INNER JOIN (
#      SELECT "obj_id" as "note_obj_id", "text" as "note"
#      FROM "meta_field_metas"
#      WHERE
#        "meta_field_metas"."obj_type" = 'Book' AND "meta_field_metas"."basename" = 'note' AND
#        ("meta_field_metas"."text" LIKE '%HOGE%' OR "meta_field_metas"."text" LIKE '%FUGA%')
#    ) ON "books"."id" = "note_obj_id"

Author.meta_join(:age: Author.meta[:age].gt(20).and(Author.meta[:age].lt(40))).order(:age)
# => SELECT "authors".*
#    FROM "authors" INNER JOIN (
#      SELECT "obj_id" as "age_obj_id", "integer" as "age"
#      FROM "meta_field_metas"
#      WHERE
#        "meta_field_metas"."obj_type" = 'Author' AND "meta_field_metas"."basename" = 'age AND
#        "meta_field_metas"."integer" > 20 AND "meta_field_metas"."integer" < 40
#     ) ON  "authors"."id" = "age_obj_id"
#     ORDER BY age


160
161
162
# File 'lib/meta_field/extension.rb', line 160

def meta
  MetaField::MetaProxy.new(self)
end

#meta_field(basename, datatype, meta_options = nil) ⇒ Object Also known as: meta_attr, meta_column

メタ属性を追加する

class Book < ActiveRecord::Base
  attr_accessible :name, :released_at, :subtitle, :note
  meta_field :released_at, :datetime
  meta_field :subtitle,    :string
  meta_field :page,        :integer,  index: false
  meta_field :note,        :text,     default: '特記事項無し'
end


103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/meta_field/extension.rb', line 103

def meta_field(basename, datatype, meta_options = nil)
  meta_options = {index: true}.merge(meta_options || {})
  meta_options[:index] = false if [:text, :binary].include?(datatype.to_sym)
  datatype = "indexed_#{datatype}" if meta_options[:index]
  meta_fields[basename.to_sym] = [datatype.to_sym, meta_options]
  class_eval <<CODE
    def #{basename}_record
      unless @attributes_cache[:#{basename}_record]
        query = metafield_metas.where(basename: #{basename.to_s.inspect})
        unless obj = query.first
          obj = query.build
          obj.#{datatype} = self.class.meta_fields[:#{basename}][1][:default]
        end
        @attributes_cache[:#{basename}_record] = obj
      end
      @attributes_cache[:#{basename}_record]
    end
    private :#{basename}_record

    def #{basename}
      #{basename}_record.#{datatype}
    end

    def #{basename}=(value)
      #{basename}_record.#{datatype} = value
    end
CODE
end