Last active
December 14, 2015 10:09
-
-
Save arthurnn/5069763 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Post | |
include Mongoid::Document | |
field :title, localize: true | |
field :subtitle, localize: true | |
include I18n | |
i18n_field :title, :subtitle | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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