Skip to content

Instantly share code, notes, and snippets.

@goldeneggg
Created October 7, 2015 06:57
Show Gist options
  • Save goldeneggg/ce6a2dc95dbc336895cd to your computer and use it in GitHub Desktop.
Save goldeneggg/ce6a2dc95dbc336895cd to your computer and use it in GitHub Desktop.
属性値の設定時に自動変換を行うconcern module
module AttributeConvertable
extend ActiveSupport::Concern
included do
# 全角英数字を半角英数字に変換
#
# (使用例.modelの定義)
# downcase_attr :hoge
#
# (使用例.modelへの値設定)
# Model.new(hoge: '123') # hoge は自動で 123 に変換して設定される
#
# md = Model.new
# md.hoge = "rtw" # hogeは自動で rtw に変換して設定される
def self.downcase_attr(name)
self.new.send("#{name}=", nil)
define_method("#{name}_with_downcase=") do |value|
value = AttributeConvertable.downcase(value)
send("#{name}_without_downcase=", value)
end
alias_method_chain "#{name}=", :downcase
end
end
def self.downcase(value)
value.tr("0-9A-Za-z", "0-9A-Za-z") if value.kind_of?(String)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment