Created
July 13, 2017 14:45
-
-
Save chuyihuang/d30def367417ae2f682307b20fdb06b1 to your computer and use it in GitHub Desktop.
在model/concern中加入enum與對應語言的方法
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
# In model: | |
# include LangMapping | |
# | |
# lang_map({ | |
# status: [[:enabled, 1, "啟動"], [:disabled, 2, "取消"], [:unauthenticated, 0, "註冊中"]], | |
# user_type: [[:standard, 0, "標準"], [:vip, 1, "高級"], [:vvip, 2, "最高級"], [:admin, 3, "管理員"]] | |
# }) | |
# 會產生 class methods: all_xxxxs, instance methods: show_xxxx 2個方法 | |
# 例如 user.show_status 會出現"啟動"、"取消"或"註冊中" | |
module LangMapping | |
extend ActiveSupport::Concern | |
module ClassMethods | |
def lang_map(settings) | |
settings.each do |setting| | |
self.define_singleton_method(%Q(enum_#{setting[0].to_s.pluralize})) do | |
setting[1].inject({}) {|collection, item| collection.merge!(item[0] => item[1])} | |
end | |
self.define_singleton_method(%Q(all_#{setting[0].to_s.pluralize})) do | |
setting[1].inject([]) do |collection, item| | |
collection << [item[2], item[0].to_s] | |
end | |
end | |
define_method(%Q(show_#{setting[0].to_s})) do | |
collections = setting[1].inject({}) do |collection, item| | |
collection.merge!(item[0].to_s => item[2]) | |
end | |
return collections[self.send(setting[0].to_s)] | |
end | |
# 產生enum :xxxx enum_xxxxs | |
enum(setting[0] => eval(%Q(enum_#{setting[0].to_s.pluralize})) ) | |
end | |
end | |
end | |
module InstanceMethods | |
end | |
def self.included(receiver) | |
receiver.extend ClassMethods | |
receiver.send :include, InstanceMethods | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment