-
github.com/#{github_username}/#{project_name}
named_attribute_parserはハッシュ形式で渡された引数をパースして返すメソッドを定義したモジュールです。
class MyClass include NamedAttributeParser def set(*args) name, age, address = named_attributes(args, name: "", age: 19, address: "TOKYO-TO") # なにか処理を行う... [name, age, address] end def block_set(*args) named_attributes(args, :name, :age, address: "TOKYO-TO") do |name, age, address| # なにか処理を行う... [name, age, address] end end end
Ruby1.9から使えるようになった名前付き引数で呼び出します。
sample = Sample.new sample.set(name: "shin", age: 36, address: "MATSUE-SHI") #=> ["shin", 36, "MATSUE-SHI"] sample.block_set(name: "shin", age: 36, address: "MATSUE-SHI") #=> ["shin", 36, "MATSUE-SHI"]
デフォルト値が与えられている場合は省略出来ます。
sample.set(name: "shin", age: 36) #=> ["shin", 36, "TOKYO-TO"]
デフォルト値が与えられていないのに値が与えられなかった場合はArguemntErrorをraiseします。
sample.set() ArgumentError: named argument 'name' is not given
テストを走らせるにはRSpecが必要です。そうでない場合は特に必要ではありません。
$ git clone git://github.com/hiroeorz/named_attribute_parser.git $ cd named_attribute_parser $ rake package (if you build yourself) # sudo gem install pkg/named_attribute_parser-0.0.1.gem
(The MIT License)
Copyright © 2011 HIROE Shin
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.