Module: HasLocalizationTable::ActiveRecord::Attributes

Defined in:
lib/has_localization_table/active_record/attributes.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

Define attribute getters and setters



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/has_localization_table/active_record/attributes.rb', line 18

def method_missing(name, *args, &block)
  if name.to_s =~ /\A([a-z0-9_]+)(=)?\Z/i
    if localized_attributes.include?($1.to_sym)
      if $2.nil? # No equals sign -- not a setter
        # Try to load a string for the given locale
        # If that fails, try for the primary locale
        raise ArgumentError, "wrong number of arguments (#{args.size} for 0 or 1)" unless args.size.between?(0, 1)
        return read_localized_attribute($1, *args) || read_localized_attribute($1, HasLocalizationTable.primary_locale)
      else
        raise ArgumentError, "wrong number of arguments (#{args.size} for 1)" unless args.size == 1
        return write_localized_attribute($1, args.first)
      end
    end
  end
  
  super
end

Instance Method Details

#read_localized_attribute(attribute, locale = HasLocalizationTable.current_locale) ⇒ Object



4
5
6
# File 'lib/has_localization_table/active_record/attributes.rb', line 4

def read_localized_attribute(attribute, locale = HasLocalizationTable.current_locale)
  attribute_cache[attribute.to_sym][locale.id] ||= localization_association.detect{ |a| a.send(HasLocalizationTable.locale_foreign_key) == locale.id }.send(attribute) rescue nil
end

#respond_to?(*args) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
# File 'lib/has_localization_table/active_record/attributes.rb', line 36

def respond_to?(*args)
  return true if args.first.to_s =~ /\A([a-z0-9_]+)=?\Z/i and localized_attributes.include?($1.to_sym)
  super
end

#write_localized_attribute(attribute, value, locale = HasLocalizationTable.current_locale) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/has_localization_table/active_record/attributes.rb', line 8

def write_localized_attribute(attribute, value, locale = HasLocalizationTable.current_locale)
  value = value.to_s
  localization = localization_association.detect{ |a| a.send(HasLocalizationTable.locale_foreign_key) == locale.id } ||
    localization_association.build(HasLocalizationTable.locale_foreign_key => locale.id)
  
  localization.send(:"#{attribute}=", value)
  attribute_cache[attribute.to_sym][locale.id] = value.blank? ? nil : value
end