Module: HstoreTranslate::Translates

Defined in:
lib/hstore_translate/translates.rb,
lib/hstore_translate/translates/instance_methods.rb,
lib/hstore_translate/translates/active_record_with_hstore_translates.rb

Defined Under Namespace

Modules: ActiveRecordWithHstoreTranslate, InstanceMethods

Constant Summary collapse

SUFFIX =
"_translations".freeze

Instance Method Summary collapse

Instance Method Details

#translates(*attrs) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hstore_translate/translates.rb', line 5

def translates(*attrs)
  include InstanceMethods

  class_attribute :translated_attribute_names, :permitted_translated_attributes

  self.translated_attribute_names = attrs
  self.permitted_translated_attributes = [
    *self.ancestors
      .select {|klass| klass.respond_to?(:permitted_translated_attributes) }
      .map(&:permitted_translated_attributes),
    *attrs.product(I18n.available_locales)
      .map { |attribute, locale| :"#{attribute}_#{locale}" }
  ].flatten.compact

  attrs.each do |attr_name|
    serialize "#{attr_name}#{SUFFIX}", ActiveRecord::Coders::Hstore unless HstoreTranslate::native_hstore?

    define_method attr_name do
      read_hstore_translation(attr_name)
    end

    define_method "#{attr_name}=" do |value|
      write_hstore_translation(attr_name, value)
    end

    define_singleton_method "with_#{attr_name}_translation" do |value, locale = I18n.locale|
      quoted_translation_store = connection.quote_column_name("#{attr_name}#{SUFFIX}")
      where("#{quoted_translation_store} @> hstore(:locale, :value)", locale: locale, value: value)
    end
  end

  send(:prepend, ActiveRecordWithHstoreTranslate)
end

#translates?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/hstore_translate/translates.rb', line 39

def translates?
  included_modules.include?(InstanceMethods)
end