user762579
user762579

Reputation:

ruby 2.2. : passing parameter to SQL request string in config yaml file

given a config file config.yml

# config.yml
folders:
   tree: 
    top: "SELECT * FROM mytable WHERE name = 'alpha'"
    bottom: "SELECT * FROM mytable WHERE name = '#{name}'"

when I execute in a ruby script :

# myscript1.rb
@config = YAML::load_file File.join( @rundir, 'config.yml')
....
@db.execute(@config['folders']['tree']['top'])

the db select is correctly executed .. how should I write my ruby command to run the second request passing 'name' as a parameter ?

# myscript2.rb
@config = YAML::load_file File.join( @rundir, 'config.yml')
....
name = "beta"
@db.execute(@config['folders']['tree']['bottom']) # need parameter ?

thanks for help

Upvotes: 0

Views: 1145

Answers (1)

Andrew Larson
Andrew Larson

Reputation: 483

For the Ruby DB interfaces I'm familiar with, you can pass arguments to execute that will be SQL escaped and interpolated into the query at points marked by ?. So, first you want to rewrite the query to: SELECT * FROM mytable WHERE name = ?;. Then, you can call @db.execute(@config['folders']['tree']['bottom'], name). Compared to Ruby string interpolation, this also has the advantage of ensuring that any untrusted parameters are properly escaped.

Upvotes: 1

Related Questions