Created
March 11, 2014 02:53
-
-
Save xixilive/9478656 to your computer and use it in GitHub Desktop.
Mongoid Utils
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 MongoidUtils | |
module RandomDocuments | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def random n = 1 | |
skip((rand * 99999999).to_i % ([count-n, 2].max)).limit(n) | |
end | |
end | |
end | |
module Localization | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def human_attribute_value attribute, value, *args | |
options = {default: value.to_s.humanize }.merge(args.extract_options!) | |
I18n.translate(:"#{self.i18n_scope}.values.#{self.model_name.i18n_key}.#{attribute}.#{value}", options) | |
end | |
def human_attribute_values_for *attrs | |
@@localization ||= {:mod => Module.new, :fields => []} | |
mod = @@localization[:mod] | |
attrs.reject!{|f| !self.fields.keys.include?(f.to_s) } | |
return if attrs.empty? | |
@@localization[:fields].concat(attrs).uniq! | |
@@localization[:fields].each do |f| | |
mod.send :define_method, :"#{f}_humanize" do | |
v = attributes[f.to_s].to_s | |
v.empty? ? v : self.class.human_attribute_value(f, v) | |
end | |
end | |
include mod | |
end | |
end | |
def human_attribute_value attr_name | |
v = self.send(attr_name) if attr_name.present? && self.respond_to?(attr_name) | |
self.class.human_attribute_value(attr_name, v) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment