LoginSignup
0
0

More than 3 years have passed since last update.

rake で 引数の与え方

Posted at

引数を与えるサンプルを作成してみました。

次のような実行結果になります。

$ rake hello['鈴木','一朗']
*** start ***
Hello Rake!!
Hello, 鈴木 一朗
Firstname, 鈴木
Lastname, 一朗
Hello, 鈴木 一朗
*** こんにちは ***
*** end ***
$ rake update[t3324,900009]
*** 開始 ***
t3324
900009
*** 終了 ***
Rakefile
# task :default => :hello
task default: :hello

desc "hello"
task :hello, 'firstname', 'lastname'
task :hello do |task,args|
    puts "*** start ***"
    puts "Hello Rake!!"
    puts "Hello, #{args['firstname']} #{args['lastname']}"
    puts "Firstname, #{args['firstname']}"
    puts "Lastname, #{args['lastname']}"
    puts "Hello, #{args['firstname']} #{args['lastname']}"
    puts "*** こんにちは ***"
    puts "*** end ***"
end
#
# ------------------------------------------------------------
desc "read"
task :read do
    require 'mysql'
    puts "*** 開始 ***"
#
    host = "127.0.0.1"
    user = "scott"
    password = "tiger123"
    data_base = 'city'
    connection = Mysql::new(host, user,password,data_base)

    sql_str = "SELECT id,name,population,date_mod FROM cities order by ID"
    begin
        result = connection.query(sql_str)
        result.each do |row|
            print "#{row[0]}\t#{row[1]}\t#{row[2]}\t#{row[3]}\n"
        end
    end
#
connection.close
#
puts "*** 終了 ***"
end
# ------------------------------------------------------------
desc "update"
task :update, 'key', 'population'
task :update do |task,args|
    require 'mysql'
    require 'date'
    puts "*** 開始 ***"
#
    key_in = "#{args['key']}"
    population_in = "#{args['population']}"
#
    puts key_in
    puts population_in
#
    host = "127.0.0.1"
    user = "scott"
    password = "tiger123"
    data_base = 'city'
    connection = Mysql::new(host, user,password,data_base)
#
    update_proc(connection,key_in,population_in)
#
    connection.commit
    connection.close
#
    puts "*** 終了 ***"
end
#
def update_proc (connection,id,population)
    date_mod=Date.today
    sql_str="UPDATE cities SET population='#{population}', DATE_MOD='#{date_mod}' where ID = '#{id}'"
    connection.query(sql_str)
end
#
# ------------------------------------------------------------

このサンプルは、mariadb にアクセスします。

使ったテーブルの様子を見るには、

$ rake read
*** 開始 ***
t3321   岡山  645927  2017-05-30
t3322   倉敷  791835  2003-02-15
t3323   津山  298999  2019-05-15
t3324   玉野  900009  2019-05-15
t3325   笠岡  237451  2003-03-04
t3326   井原  518397  2003-05-21
t3328   高梁  478231  2003-10-26
t3329   新見  863751  2003-12-15
*** 終了 ***
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0