Using File::read in a provider's default.rb in Chef - ruby

I am trying to create an LWRP that will call the resource that is defined within itself. My cookbook's structure is as follows:
In the machine cookbook's provider, I have a code snippet as follows:
require 'chef/provisioning' # driver for creating machines
require '::File'
def get_environment_json
##environment_template = JSON.parse(File::read(new_resource.template_path + "environment.json"))
return ##environment_template
end
The code is only trying to read a json file and I am using File::read for it.
I keep getting an error as follows:
LoadError
cannot load such file -- ::File
Does anyone know how I can use File::read inside my LWRP's provider?

OK, so the prior two answers are both half right. You have two problems.
First, you can't require ::File as it's already part of Ruby. This is the cause of your error.
Second, if you call File.read you will grab Chef's File not ruby's. You need to do a ::File.read to use Ruby's File class.

require '::File'
Is incorrect and is causing the LoadError. Delete this line. You don't need it. File is part of the Ruby core and doesn't need to be required.
To further explain, the string argument to require represents the file name of the library you want to load. So, it should look like require "file", or require "rack/utils".

It happens becuase Chef already has a file resource. We have to use the Ruby File class in a recipe.We use ::File to use the Ruby File class to fix this issue. For example:
execute 'apt-get-update' do
command 'apt-get update'
ignore_failure true
only_if { apt_installed? }
not_if { ::File.exist?('/var/lib/apt/periodic/update-success-stamp') }
end
Source: https://docs.chef.io/ruby.html#ruby-class

Related

WEBrick run on hanami 1.0.0 shows errors because of wrong inflection

I generated model with hanami generate model stimulus. Then I fixed "stimuluses" to "stimuli" in the migration file name and inside, the table name.
Everytime I load a page I get this error in the server console window:
[ROM::Relation[Stimuluses]] failed to infer schema. Make sure tables exist before ROM container is set up. This may also happen when your migration tasks load ROM container, which is not needed for migrations as only the connection is required (schema parsing returned no columns, table "stimuluses" probably doesn't exist)
I looked into the libraries and found that this functionality has Inflecto library. Then I tried both adding to hanami project this:
# /config/initializers/inflecto.rb
require 'inflecto'
Inflecto.inflections do |inflect|
inflect.irregular('stimulus', 'stimuli')
end
And editing the defualt library file:
# gems/inflecto-0.0.2/lib/inflecto/defaults.rb
Inflecto.inflections do |inflect|
...
inflect.irregular('stimulus', 'stimuli')
...
end
But the message is still there after restarting the server.
Is this something I should solve and if yes, how to do this?
EDIT:
Also tried:
# /config/initializers/inflector.rb
require 'hanami/utils/inflector'
Hanami::Utils::Inflector.inflections do
exception 'stimulus', 'stimuli'
end
I'm assuming we are talking about Hanami v1.0.0, right?
You nearly succeeded. What hit you is that initializers seem to be not loaded when executing hanami commands and maybe a bug in code reloading. So instead of an initializer put it into a file that gets loaded when hanami commands are executed or require the initializer file in such a place. E.g.,
# config/initializers/inflections.rb
require 'hanami/utils/inflector'
Hanami::Utils::Inflector.inflections do
exception 'stimulus', 'stimuli'
end
and then in your environment file
# config/environment.rb
# ...
require_relative 'initializers/inflections.rb'
# ...
I'm not sure if that is a good place to put custom inflection rules, but at least it works.

Ruby script, best method to store login information for an API?

I'm currently working on a script (command line tool) for work to help me manage expose consoles.
At first I was passing three arguments to the script each time I used it to login into the consoles, for example:
$ nexose-magic.rb -u user -p password -i 192.168.1.2 --display-scans
It's not very efficient, so I created a config.yml file that stores console information in a hash.
$ nexpose-magic.rb -c console --display-scans
I believe the tool will be useful to admins out there, so I'd like to share it in a gem. I can't figure out how to get my config.yml file to work with a gem install..It can't find the config.yml file! It's easy to point it at the relative path in my development directory, but once I create a gem that relative path isn't so relative anymore. How do I point nexpose-magic.rb at the config.yml file?
Is there a better way to handle something like this?
You can create a gem that include a configure class. This class has a load method that will take a directory as an argument. Then, you can pass the directory where you are currently working.
A nice way of preparing your gem is to create a Configuration singleton class in your gem:
require 'singleton'
class Configuration
include Singleton
attr_accessor :config, :app_path
def load(app_path)
#app_path = app_path
#load the config file and store the data
#config = YAML.load_file( File.join(#app_path,'config','config.yml'))
end
end
In your main class :
module MyFancyGem
class << self
#define a class method that configure the gem
def configure(app_path)
# Call load method with given path
config.load(app_path)
end
# MyFancyGem.config will refer to the singleton Configuration class
def config
MyFancyGem::Configuration.instance
end
end
end
Usage:
-Working directory
- my_new_script
- Gemfile
- config/
- config.yml
In my_new_script :
require 'bundler'
Bundler.setup(:default)
require 'my_fancy_gem'
MyFancyGem.configure(File.join(File.dirname(__FILE__),"./")) #here, you define the path
MyFancyGem.hello_world
I hope that's clear enough. I was actually about to write a blog post to explain this particular point (I hope in a more complete version of it). Let me know if you're interested !

Creating Ruby Main (command line utility) program with multiple files

I am trying to use the main gem for making command line utilities. This was presented in a recent Ruby Rogues podcast.
If I put all the code in one file and require that file, then rspec gives me an error, as the main dsl regards rpsec as a command line invocation of the main utility.
I can break out a method into a new file and have rspec require that file. Suppose you have this program, but want to put the do_something method in a separate file to test with rspec:
require 'main'
def do_something(foo)
puts "foo is #{foo}"
end
Main {
argument('foo'){
required # this is the default
cast :int # value cast to Fixnum
validate{|foo| foo == 42} # raises error in failure case
description 'the foo param' # shown in --help
}
do_something(arguments['foo'].value)
}
What is the convenient way to distribute/deploy a ruby command line program with multiple files? Maybe create a gem?
You are on the right track for testing - basically you want your "logic" in separate files so you can unit test them. You can then use something like Aruba to do an integration test.
With multiple files, your best bet is to distribute it as a RubyGem. There's lots of resources out there, but the gist of it is:
Put your executable in bin
Put your files in lib/YOUR_APP/whatever.rb where "YOUR_APP" is the name of your app. I'd also recommend namespacing your classes with modules named for your app
In your executable, require the files in lib as if lib were in the load path
In your gemspec, make sure to indicate what your bin files are and what your lib files are (if you generate it with bundle gem and are using git, you should be good to go)
This way, your app will have access to the files in lib at runtime, when installed with RubyGems. In development, you will need to either do bundle exec bin/my_app or RUBYLIB=lib bin/my_app. Point is, RubyGems takes care of the load path at runtime, but not at development time.

Call one Ruby Script from Another

I am having a perplexing problem. I want to call one ruby script from another.
With this in mind, I create a testscript.rb and executed it, it contains this code,
require './paypal.rb'
puts paypal['L_AMT0']
This code returns a number, which is my paypal balance. It relies on a paypal.rb file which uses the ruby-paypal gem. When I do ruby testscript.rb I get the output of my paypal balance, which means it is working properly. This tells me that my method for calling one RB from another is okay, since, in the above scenario, testscript.rb is getting a variable that is returned from paypal.rb.
Using this same logic, I inserted the above code into another program which is called SiriProxy. It is a ruby program. I need it to get my paypal balance.
So Inside that program, I did a require paypal.rb, it failed because it could not find it, so I set an absolute path in require which fixed it.
However, when SiriProxy (the other ruby rb giving me an issue) trys to run puts paypal['L_AMT0'] it results in an error and ends the program.
This is the error,
[Info - Plugin Manager] Say: Checking Paypal Balance
/home/siriproxy/.rvm/gems/ruby-1.9.3-p194#SiriProxy/gems/siriproxy-0.3.0/plugins/siriproxy-example/lib/siriproxy-example.rb:47:in `block in <class:Example>': undefined local variable or method `paypal' for #<SiriProxy::Plugin::Example:0x931a228> (NameError)
from /home/siriproxy/.rvm/gems/ruby-1.9.3-p194#SiriProxy/bundler/gems/cora-1edcfb9073d5/lib/cora/plugin.rb:47:in `instance_exec'
from /home/siriproxy/.rvm/gems/ruby-1.9.3-p194#SiriProxy/bundler/gems/cora-1edcfb9073d5/lib/cora/plugin.rb:47:in `block (2 levels) in process'
In the above output it appears the issue is it does not understand "paypal", as seen here:
undefined local variable or method `paypal'
However, I do not understand why, since in testscript.rb I do the exact same thing and it works.
Can anyone help? Thank you.
Seems like #CodeGnome is right.
From the Kernel documentation:
require(name) → true or false
Loads the given name, returning true if successful and false if the
feature is already loaded.
require_relative(string) → true or false
Ruby tries to load the library named string relative to the requiring
file’s path. If the file’s path cannot be determined a LoadError is
raised. If a file is loaded true is returned and false otherwise.
Loading Files from the Current Directory
I don't know anything about your library or its internals, but it looks like your require statement may be wrong. If you want to load a file from the current directory in Ruby 1.9.3, you should use:
require_relative 'paypal'
Bundler and Gems
If it's a gem that you've installed as part of a bundle (e.g. the gem is defined in a Gemfile), then providing a path in your require statement is wrong. Instead, you need to require the bundled gem as follows:
require 'bundler/setup'
require 'paypal'

Ruby require a code snippet from github

Is there anyway to get Ruby's require statement to download a file from somewhere like github rather than just the local file system?
Update: Sorry I should have made the question clearer. I want to download a file that contains Ruby module and import it into my script rather than just downloading an image or some other arbitrary file within my script.
In other words something like this
require 'http:\\github.com\myrepo\snippet.rb'
puts 'hi'
By default, this is not possible. Also, it's not a good idea for security reasons.
You have a couple of alternatives. If the file you want to include is a Gem and Git repository, then you can use Bundler to download and package the dependency in your project. Then you'll be able to require the file directly in your source code.
This is the best and safest way to include an external dependency.
If you trust the source and you really know what you are doing, you can download the file using Net::HTTP (or any other HTTP library) and eval the body directly in your Ruby code.
You can package everything in a custom require_remote function.
You could download and eval it
require "open-uri"
alias :require_old :require
def require(path)
return false if $".include?(path)
unless path=~ /\Ahttp:\/\/
return require_old(path)
end
eval(open(path).read)
$"<< path
true
end
Be aware, this code has no error checking for network outages nonexisting files, ... . I also believe it is in general not a good idea to require libraries this way, there are security and reliability problems in this approach. But maybe you have a valid usecase for this.
you can include a remote gem from within Gemfiles then it will download when you run bundle install
After reading this question and answers I wanted something a little more bullet proof and verbose that used a paradigm of creating a local file from a repo and then requiring it, only if it didn't already exist locally already. The request for the repo version is explicit via the method repo_require. Used on files you control, this approach improves security IMO.
# try local load
def local_require(filename, relative_path)
relative_flname = File.join(relative_path, filename)
require_relative(relative_flname)
end
# try loading locally first, try repo version on load error
# caution: only use with files you control access to!
def repo_require(raw_repo_prefix, filename, relative_path = '')
local_require(filename, relative_path)
rescue LoadError => e
puts e.message
require 'open-uri'
tempdir = Dir.mktmpdir("repo_require-")
temp_flname = File.join(tempdir, File.basename(filename))
return false if $LOADED_FEATURES.include?(temp_flname)
remote_flname = File.join(raw_repo_prefix, filename)
puts "file not found locally, checking repo: #{remote_flname}"
begin
File.open(temp_flname, 'w') do |f|
f.write(URI.parse(remote_flname).read)
end
rescue OpenURI::HTTPError => e
raise "Error: Can't load #{filename} from repo: #{e.message} - #{remote_flname}"
end
require(temp_flname)
FileUtils.remove_entry(tempdir)
end
Then you could call repo_require like this:
repo_require('https://raw.githubusercontent.com/username/reponame/branch',
'filename', 'relative_path')
The relative_path would the the relative path you would use for the file if the repo was locally installed. For example, you may have something like require_relative '../lib/utils.rb'. In this example filename='lib/utils.rb' and relative_path='..'. This information allows the repo url to be constructed correctly as it does not use the relative path portion.

Resources