Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Last active December 14, 2015 10:09
Show Gist options
  • Save arthurnn/5069763 to your computer and use it in GitHub Desktop.
Save arthurnn/5069763 to your computer and use it in GitHub Desktop.
module I18n
extend ActiveSupport::Concern
included do
attr_accessor :forced_locale
end
module ClassMethods
def i18n_field(*syms)
syms.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
self.#{sym}_translations[@forced_locale.to_s] || super
end
def #{sym}=(v)
if @forced_locale
self.#{sym}_translations = (self.#{sym}_translations || {}).merge(@forced_locale.to_s => v)
else
super(v)
end
end
EOS
end
end
end
end
class Post
include Mongoid::Document
field :title, localize: true
field :subtitle, localize: true
include I18n
i18n_field :title, :subtitle
end
require 'spec_helper'
describe Post do
let(:post) do
Post.create!
end
subject { post }
context "when using hash" do
before do
post.title_translations = {'en' => 'hello', 'fr' => 'merci'}
post.save!
post.reload
end
it do
post.reload.title_translations.should eq({'en' => 'hello', 'fr' => 'merci'})
end
end
context "when using title property" do
before do
post.forced_locale = 'en'
post.title = 'hello'
post.forced_locale = 'fr'
post.title ='merci'
end
its "title_translations" do
should eq({'en' => 'hello', 'fr' => 'merci'})
end
it do
post.save!
post.reload
post.title_translations.should eq({'en' => 'hello', 'fr' => 'merci'})
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment