Sha256: 3a023684bc0f6ec02c4489929295ffded152defff37252ad93d9e16783612bc0
Contents?: true
Size: 1.33 KB
Versions: 15
Compression:
Stored size: 1.33 KB
Contents
# frozen_string_literal: true # Add support for `translates(*attributes)` macro, which # uses JSONB to store translations of the specified attrs. module Maglev module Translatable class UnavailableLocaleError < RuntimeError; end extend ActiveSupport::Concern def translations_for(attr) public_send("#{attr}_translations") end class_methods do def order_by_translated(attr, direction) order(Arel.sql("#{attr}_translations->>'#{Maglev::I18n.current_locale}'") => direction) end def translates(*attributes, presence: false) attributes.each { |attr| setup_accessors(attr) } add_presence_validator(attributes) if presence end private def add_presence_validator(attributes) validate do attributes.each do |attribute| errors.add(attribute, :blank) if public_send(attribute).blank? end end end def setup_accessors(attr) define_method("#{attr}=") do |value| public_send("#{attr}_translations=", translations_for(attr).merge(Maglev::I18n.current_locale => value)) end define_method(attr) { translations_for(attr)[Maglev::I18n.current_locale.to_s] } define_method("default_#{attr}") { translations_for(attr)[Maglev::I18n.default_locale.to_s] } end end end end
Version data entries
15 entries across 15 versions & 1 rubygems