Skip to content

Instantly share code, notes, and snippets.

@adeonhy
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeonhy/98c799298d099c0a05e0 to your computer and use it in GitHub Desktop.
Save adeonhy/98c799298d099c0a05e0 to your computer and use it in GitHub Desktop.
module FieldAlias
#列挙タイプのエイリアス定義
#ex define_alias_enum(:original, :alias, {0 => "NG", 1 => "OK", nil => "-", other: "不明"})
###from
#def receipt_status
# case receipt
# when 0
# "-"
# when 1
# "必要"
# when 2
# "不要"
# else
# "不明な値"
# end
#end
###to
#define_alias_enum(:receipt, :receipt_status, {0 => "-", 1 => "必要", 2 => "不要", other: "不明な値"})
def define_alias_enum(method_name, alias_name, args)
define_method alias_name do
value = self.send method_name
if args.has_key? value
args[value]
elsif args.has_key? :other
args[:other]
end
end
end
#nil値を別の値にするタイプのエイリアス定義
#ex1 define_alias_nil(:original, :alias, "-")
#ex2 define_alias_nil(:original, :alias, "-") {|v| v.upcase }
def define_alias_nil(method_name, alias_name, nilvalue, &block)
define_method alias_name do
value = self.send(method_name)
if value
block_given? ? yield(value) : value
else
nilvalue
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment