Sha256: ba31b233c7f83bd87b3f886d5924bc654eae3c02fcb1de4880178bc2ef312bcd
Contents?: true
Size: 1.51 KB
Versions: 2
Compression:
Stored size: 1.51 KB
Contents
module TranslatableRecords class Builder attr_reader :model, :concern def initialize(model) @model = model @concern = Module.new do extend ActiveSupport::Concern include Concern end end def define(attributes) ensure_association attributes.each do |attribute| define_writer attribute define_readers attribute model.translations << attribute end model.include concern end private def ensure_association unless model.reflections.has_key?(:translations) model.has_many( :translations, class_name: "#{model.name}Translation", dependent: :destroy ) model.accepts_nested_attributes_for :translations end end def define_writer(attribute) name = "#{attribute}=" concern.class_eval do define_method name do |value| if translation = find_translation(locale) translation.send name, value else translations.build(locale: locale, attribute => value) end end end end def define_readers(attribute) names = [ attribute, "#{attribute}_was", "#{attribute}_changed?", "#{attribute}_before_type_cast", "#{attribute}_came_from_user?" ] concern.class_eval do names.each do |name| define_method name do find_translation(locale).try name end end end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
translatable_records-5.1.0 | lib/translatable_records/builder.rb |
translatable_records-4.0.0.1 | lib/translatable_records/builder.rb |