I'm doing a simple Net:LDAP search and when I'm outputting an entry's attribute that may not exist for every entry, I get an error "NoMethodError: undefined method 'some_attribute'"
Here is the code:
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new
ldap.host = 'ldap.example.com'
ldap.port = 389
if ldap.bind
filter = Net::LDAP::Filter.eq( "sn", "Smith" )
treebase = "ou=people,o=company"
ldap.search( :base => treebase, :filter => filter, :return_result => false) do |entry|
puts #{entry.some_attribute}
end
end
else
puts "bind unsuccessful"
end
I tried also doing:
if entry.respond_to?(some_attribute)
puts "#{entry.some_attribute}"
end
That didn't work, it returns as false for every entry (when some entries have the attribute).
Ruby is expecting a symbol in the respond_to? method call.
ruby-1.8.7-p299 > class Foo
ruby-1.8.7-p299 ?> attr_accessor :some_attr
ruby-1.8.7-p299 ?> end
=> nil
ruby-1.8.7-p299 > Foo.new.respond_to?(some_attr)
NameError: undefined local variable or method `some_attr' for #<Object:0xb77ce950>
from (irb):4
ruby-1.8.7-p299 > Foo.new.respond_to?(:some_attr)
=> true
Related
i try to call my methode check_table_exists for check my table. This methode is on my module, and i dont understand why i get this error .
i know #connexion is a Mysql2::Client instance, which doesn't include the module Sgbd. but i dont see how to include my methode ?
./yamlReadFile.rb:44:in `mysql_connection': undefined method `check_table_exists' for #<Mysql2::Client:0x000000033a7750> (NoMethodError)
$LOAD_PATH << '.'
require 'yaml'
require 'rubygems'
require 'mysql2'
require 'creatDatabase'
#binding.pry
class StreamMysql
include Sgbd
def mysql_connection(conf)
#connexion = Mysql2::Client.new(:host => conf['ost'], :username => conf['user'], :password => conf['password'], :table => conf['table'], :port => conf['port'])
if #connexion
puts check_table_exists
#connexion.check_table_exists
puts "connexion etablie"
else
puts "error connexion"
end
rescue Mysql2::Error => e
puts e.errno
puts e.error
#connexion.close
end
def read_config_file
config = YAML::load_file(File.join(__dir__, 'config.yml'))
conf = config['database']
mysql_connection(conf)
end
end
my module file with the mehode check_table_exists
module Sgbd
# class ModuleCreateDatabase
def create_database
end
def check_table_exists
query=("SHOW TABLES;")
end
end
It’s unclear why would you want to include your module in the foreign class, but it’s doable:
Mysql2::Client.include Sgbd
The line above should be put e. g. before class StreamMysql declaration.
I have the following little script that connects to a host, and gets some output.
#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'timeout'
serverurl = "http://www.google.com/"
uri = URI(serverurl)
res = Net::HTTP.post_form(uri, 'method' => 'login', 'username' => 'admin', 'password' => 'MySup3rDup3rp#55w0rd')
cookie = res['set-cookie']
if cookie.nil?
puts "No cookie"
end
I want to use some timeout so I do:
#!/usr/bin/env ruby
require 'net/http'
require 'net/https'
require 'timeout'
serverurl = "http://www.google.com/"
uri = URI(serverurl)
begin
timeout(10) do
res = Net::HTTP.post_form(uri, 'method' => 'login', 'username' => 'admin', 'password' => 'MySup3rDup3rp#55w0rd')
end
rescue StandardError,Timeout::Error
puts "#{server} Timeout"
exit(1)
end
cookie = res['set-cookie']
if cookie.nil?
puts "No cookie"
end
Now I get some error:
test.rb:20:in `<main>': undefined local variable or method `res' for main:Object (NameError)
I don't know why, because a similar test code works without error:
require "timeout"
begin
timeout(6) do
sleep
end
#rescue # under ruby >= 1.9 is ok
rescue StandardError,Timeout::Error # workaround for ruby < 1.9
p "I'm sorry, Sir. We couldn't make it, Sir."
end
Any idea what am I doing wrong?
This is about scope. In Ruby, variables are only visible within the same scope where they are defined (exceptions are instance-, class-, and global variables as well as constants).
So in your example, res is only visible within the timeout-block. Add res = nil before the begin-block to make sure res is defined in the scope you actually need the value.
I'd like to use a Ruby Module to store a set of configuration defaults.
I'm having some problems using the values and hope someone could help.
This may not be the best way to do this but this is what I've come up with so far.
Here is a module to hold value for a persons Resume => resume.rb
module Resume
require 'ostruct'
attr_reader :personal, :education
#personal = OpenStruct.new
#education = Array.new
def self.included(base)
set_personal
set_education
end
def self.set_personal
#personal.name = "Joe Blogs"
#personal.email_address = 'joe.blogs#gmail.com'
#personal.phone_number = '5555 55 55 555'
end
def self.set_education
#education << %w{ School\ 1 Description\ 1 }
#education << %w{ School\ 2 Description\ 2 }
end
end
From irb it works fine:
% irb -I .
1.9.3-p194 :001 > require 'resume'
=> true
1.9.3-p194 :002 > include Resume
=> Object
1.9.3-p194 :003 > puts Resume.personal.name
Joe Blogs
=> nil
However when I include this into a class it throws and error => build.rb
require 'resume'
class Build
include Resume
def build
puts Resume.personal.name
end
end
From irb:
% irb -I .
1.9.3-p194 :001 > require 'build'
=> true
1.9.3-p194 :002 > b = Build.new
=> #<Build:0x00000001d0ebb0>
1.9.3-p194 :003 > b.build
NoMethodError: undefined method `personal' for Resume:Module
from /home/oolyme/projects/lh_resume_builder_ruby/build.rb:7:in `build'
from (irb):3
from /home/oolyme/.rvm/rubies/ruby-1.9.3-p194/bin/irb:16:in `<main>'
I've tried a few variations to output the include module variables in the Build class instance but all error out.
attr_accessor creates a couple of instance methods, meaning that they will be available on an instance of Build. But you clearly want class instance methods. Change definition of your module to this:
module Resume
require 'ostruct'
def self.personal
#personal
end
def self.education
#education
end
def self.included(base)
#personal = OpenStruct.new
#education = Array.new
set_personal
set_education
end
def self.set_personal
#personal.name = "Joe Blogs"
#personal.email_address = 'joe.blogs#gmail.com'
#personal.phone_number = '5555 55 55 555'
end
def self.set_education
#education << %w{ School\ 1 Description\ 1 }
#education << %w{ School\ 2 Description\ 2 }
end
end
And it'll work
b = Build.new
b.build # >> Joe Blogs
If I define the following model...
class Foo
include DataMapper::Resource
property :name, String, :key => true
before :save, do
puts 'save'
end
before :update, do
puts 'update'
end
end
Why does the 2nd save also trigger the 'update' hook?
ruby :001 > f = Foo.new
=> #<Foo #name=nil>
ruby :002 > f.name = 'Bob'
=> "Bob"
ruby :003 > f.save
save
=> true
ruby :004 > f.name = 'Joe'
=> "Joe"
ruby :005 > f.save
save
update
=> true
Of course I could dive into the source and answer the question of what code drives this behavior. More importantly, I want to understand the right way to use each of these hooks in practice.
require 'rubygems'
require 'data_mapper'
class Foo
include DataMapper::Resource
property :name, String, :key => true
before :create, do
puts 'Create: Only happens when saving a new object.'
end
before :update, do
puts 'Update: Only happens when saving an existing object.'
end
before :save, do
puts 'Save: Happens when either creating or updating an object.'
end
before :destroy, do
puts 'Destroy: Only happens when destroying an existing object.'
end
end
DataMapper.setup :default, 'sqlite::memory:'
DataMapper.finalize
DataMapper.auto_migrate!
puts "New Foo:"
f = Foo.new :name => "Fighter"
f.save
puts "\nUpdate Foo:"
f.name = "Bar"
f.save
puts "\nUpdate Foo again:"
f.update :name => "Baz"
puts "\nDestroy Foo:"
f.destroy
Which returns:
New Foo:
Save: Happens when either creating or updating an object.
Create: Only happens when saving a new object.
Update Foo:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.
Update Foo again:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.
Destroy Foo:
Destroy: Only happens when destroying an existing object.
So as you can see you'd want to use :save hooks whenever something should happen after either a create or an update, and :create and/or :update when you want a finer level of control.
EDIT: forgot to include my environment info... Win7x64, RubyInstaller Ruby v1.9.1-p378
EDIT 2: just updated to v1.9.1, patch 429, and still getting this same error.
Edit 3: running this same code in Ruby v1.8.7, patch 249, works fine. so it's v1.9.1 that broke it, apparently.
I'm new to using ERB and the samples i could find are... ummm... less than helpful... having played around with ERB for about an hour, I got some basic examples working (finally), but I have no idea why this doesn't work...
require 'ostruct'
require 'erb'
data = {:bar => "bar"}
vars = OpenStruct.new(data)
template = "foo "
erb = ERB.new(template)
vars_binding = vars.send(:binding)
puts erb.result(vars_binding)
this code produces the following error:
irb(main):007:0> puts erb.result(vars_binding)
NameError: undefined local variable or method `bar' for main:Object
from (erb):1
from C:/Ruby/v1.9.1/lib/ruby/1.9.1/erb.rb:753:in `eval'
from C:/Ruby/v1.9.1/lib/ruby/1.9.1/erb.rb:753:in `result'
from (irb):7
from C:/Ruby/v1.9.1/bin/irb:12:in `'
why is it looking at the main:Object binding? I told it to use the binding from the OpenStruct by passing in vars_binding
can someone fill me in on why it doesn't work, and help me get it to work?
The problem is where the binding is being executed. The 1.8.7-way obj.send(:binding) does not work anymore (see issue2161), the environment must be the object itself. So use instance_eval:
require 'ostruct'
require 'erb'
namespace = OpenStruct.new(:first => 'Salvador', :last => 'Espriu')
template = 'Name: <%= first %> <%= last %>'
ERB.new(template).result(namespace.instance_eval { binding })
#=> Name: Salvador Espriu
More about this issue in this answer.
Fix to Problem:
I stumbled upon this question when encountering the same type of error with similar code in Ruby 1.9.2.
I'm new to Ruby so I can't explain what is happening. I continued to search online and found this blog post that has an approach that seems to work. After modifying your example to incorporate this approach I end up with the following, working, code:
require 'ostruct'
require 'erb'
class ErbBinding < OpenStruct
def get_binding
return binding()
end
end
data = {:bar => "baz"}
vars = ErbBinding.new(data)
template = "foo <%= bar %>"
erb = ERB.new(template)
vars_binding = vars.send(:get_binding)
puts erb.result(vars_binding)
Additional Information:
When the code is run thru the IRB, I get:
require 'ostruct'
=> true
require 'erb'
=> true
class ErbBinding < OpenStruct
def get_binding
return binding()
end
end
=> nil
data = {:bar => "baz"}
=> {:bar=>"baz"}
vars = ErbBinding.new(data)
=> #<ErbBinding bar="baz">
template = "foo <%= bar %>"
=> "foo <%= bar %>"
erb = ERB.new(template)
=> #<ERB:0x2b73370 #safe_level=nil, #src="#coding:IBM437\n_erbout = ''; _erbout.concat \"foo \"; _erbout.concat(( bar ).to_s); _erbout.force_encoding(__ENCODING__)", #enc=#<Encoding:IBM437>, #filename=nil>
vars_binding = vars.send(:get_binding)
=> #<Binding:0x2b6d418>
puts erb.result(vars_binding)
foo baz
=> nil
What's your environment look like? This code worked for me (I just changed the string "bar" to "baz" to disambiguate in my brain, and added it to the template):
require 'ostruct'
require 'erb'
data = {:bar => "baz"}
vars = OpenStruct.new(data)
template = "foo <%= bar %>"
erb = ERB.new(template)
vars_binding = vars.send(:binding)
puts erb.result(vars_binding)
When I run it, I get:
defeateds-MacBook-Pro:Desktop defeated$ ruby erb.rb
foo baz
Under 1.8.7 on OSX:
defeateds-MacBook-Pro:Desktop defeated$ ruby -v
ruby 1.8.7 (2009-06-08 patchlevel 173) [universal-darwin10.0]
Looks like this does not work with higher ruby versions
with ruby 2.1.1
[19] pry(main)> name = "samtoddler"
=> "Suresh"
[20] pry(main)> template_string = "My name is <%= name %>"
=> "My name is <%= name %>"
[21] pry(main)> template = ERB.new template_string
=> #<ERB:0x007fadf3491c38
#enc=#<Encoding:UTF-8>,
#filename=nil,
#safe_level=nil,
#src="#coding:UTF-8\n_erbout = ''; _erbout.concat \"My name is \"; _erbout.concat(( name ).to_s); _erbout.force_encoding(__ENCODING__)">
[22] pry(main)> puts template.result
NameError: undefined local variable or method `name' for main:Object
from (erb):1:in `<main>'
with ruby 1.9.3
[2] pry(main)> name = "samtoddler"
=> "Suresh"
[3] pry(main)> template_string = "My name is <%= name %>"
=> "My name is <%= name %>"
[4] pry(main)> template = ERB.new template_string
=> #<ERB:0x007f9be2a1fdf8
#enc=#<Encoding:UTF-8>,
#filename=nil,
#safe_level=nil,
#src=
"#coding:UTF-8\n_erbout = ''; _erbout.concat \"My name is \"; _erbout.concat(( name ).to_s); _erbout.force_encoding(__ENCODING__)">
[5] pry(main)> puts template.result
My name is samtoddler
So it gives error but still works in 1.9.3 and all the versions below 1.9.3.