ruby - Temporarily switch MongoMapper to read from slave replicas -


i'm using mongomapper our primary datastore, , want run reporting jobs against slave nodes in our replica set, rather primary. unfortunately, of our background jobs read/write , need go against primary.

is there way can following:

mongomapper.options({:slave_ok => true})  report.fetch_data  # sorts of stuff, uses normal models, developer doesn't have go out of his/her way specify read preference  mongomapper.options({:slave_ok => force}) 

right looks mongomapper wants set read preference bring connection , not change after that.

mm doesn't natively support this, wouldn't hard on per-model basis via plugin.

module mongomapper   module plugins     module readpreference       extend activesupport::concern        included         class << self           attr_accessor :read_preference         end       end        module classmethods         def query(options={})           options.merge!(:read => read_preference) if read_preference           super options         end          def with_read_preference(preference)           self.read_preference = preference           begin             yield           ensure             self.read_preference = nil           end         end       end     end   end end  mongomapper::document.plugin(mongomapper::plugins::readpreference) 

and testing master-only cluster:

2.0.0p0 :002 > user.first  => <user:0x30a1948 _id: 4cddf1ff98db746691000002, display_name: (deleted account)> 2.0.0p0 :003 > user.with_read_preference(:secondary) { user.first } mongo::connectionfailure: no replica set member available query read preference matching mode secondary , tags matching []. 

it works!

if wanted setting global connection, extend mongomapper module module attribute, , modify plugin first, well.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -