How to use ohai gem - ruby

In the OpsCode Wiki there is there following documentation:
require 'ohai'
# ...
# Profit! ;-)
How can I print the JSON data provided by the 'ohai' command but using IRB? I tried to see the code in application.rb but I get empty data.
require 'ohai/application'
ohai = Ohai::System.new
ohai.json_pretty_print
=> "{\n\n}"
I am not trying to do this within Chef (or Shef), I just want to use the ohai gem itself, in my own app.

Poking about in the Ohai::Application class (what you get when you run ohai), #run_application instantiates Ohai::System and, unless it was configured by a file, it calls all_plugins to populate it with data.
Presumably, Ohai::System#all_plugins delegates the data collection to the lib/ohai/plugins directory.
$ irb -rohai
> system = Ohai::System.new
=> #<Ohai::System:0x00000100988950 #data={}, #seen_plugins={}, #providers={}, #plugin_path="", #hints={}>
> system.all_plugins
=> true
> puts system.to_json
{"languages":{"ruby":{"platform":"x86_64-darwin10.8.0","version":"1.9.2", ...
> system.to_json.size
=> 42395

I too searched for a simple and good library to do that...
I came across
Usagewatch
and after 5 minutes had my monitoring.rb done..
Install : gem install usagewatch
Install on mac : gem install usagewatch_ext
Refer to this article for more info

Related

How to enable redis for Dashing?

I use free heroku instance to run my Dashing project. In result, it looses the value passed previously, when my instance sleeps. I was recommended to use Redis to keep history. I tryed to follow the instruction given here. In result I got the following config.ru (as part of my dashing project):
require 'dashing'
require 'redis-objects'
require 'yaml'
configure do
set :auth_token, 'my-token'
set :default_dashboard, 'def' # https://github.com/Shopify/dashing/wiki/How-To:-Change-the-default-dashboard
helpers do
def protected!
# Put any authentication code you want in here.
# This method is run before accessing any resource.
end
end
end
def redis?
ENV.has_key? 'REDISTOGO_URL'
end
if redis?
redis_uri = URI.parse(ENV['REDISTOGO_URL'])
Redis.current = Redis.new(:host => redis_uri.host,
:port => redis_uri.port,
:password => redis_uri.password)
set :history, Redis::HashKey.new('dashing-history')
elsif File.exists?(settings.history_file)
set history: YAML.load_file(settings.history_file)
else
set history: {}
end
map Sinatra::Application.assets_prefix do
run Sinatra::Application.sprockets
end
run Sinatra::Application
and the following Gemfile:
source 'https://rubygems.org'
gem 'dashing'
gem 'redis-objects'
## Remove this if you don't need a twitter widget.
gem 'twitter', '>= 5.9.0'
But it didn't help. What I did incorrectly?
I also tried to use this tutorial. But it was giving me an error at line redis_uri = URI.parse(ENV["REDISTOGO_URL"]) (something like wrong url is given).
The problem was that the app requires the add-on Redis To Go
If Redis To Go is configured, REDISTOGO_URL is added to environment variables, it will work
For more information on how to setup Redis To Go, read the heroku article
Adding Redis to an application provides benefits, you may be using RedisToGo to power simple Resque or Sidekiq jobs, or using the raw power of Redis 2.6 Lua Scripting to do some crazy fast operations. Redis can be used a database, but it’s often used as a complementary datastore. With over 140 commands, the possibilities are endless.

Puppet: generate statement fails when trying to retrieve default path of an executable

I have built a stanza to remove a ruby gem package from our servers. The problem is that the ruby gem executable is installed in different paths on the servers, so on one server it could be in /opt/ruby/bin/gem on other servers it's in /usr/local/rvm/rubies/ruby-2.0.0-p353/bin/gem
My stanza uses the generate function in puppet to pull out the default ruby gem installation as follows:
$ruby_gem_location = generate('which', 'gem')
exec { "remove-remote_syslog":
command => "gem uninstall remote_syslog",
path => "$ruby_gem_location:/opt/ruby/bin:/usr/bin:/usr/sbin",
onlyif => "$ruby_gem_location list|grep remote_syslog"
}
When I run puppet agent I get the following error:
Generators must be fully qualified at ****redacted*
I have also tried to provide a default path for the which command as follows:
$ruby_gem_location = generate('/usr/bin/which', 'gem')
and now the error says : Could not evaluate: Could not find command '/usr/bin/gem
I checked the target server and the gem command is in
/usr/local/rvm/rubies/ruby-2.0.0-p353/bin/gem
What am I doing wrong?
How can I pull out the default ruby gem location on our servers?
Thank you in advance
Your code
$ruby_gem_location = generate('/usr/bin/which', 'gem')
will generate a full path to your gem command (if it succeeds). From the result you describe, I think it is generating '/usr/bin/gem', which is perhaps a symlink to the real gem command. You are putting that into your command path instead of just the directory part, and that will not be helpful. It is not, however, the source of the error message you report.
The real problem here is that generate(), like all DSL fucntions, runs during catalog building. I infer from your results that you are using a master / agent setup, so generate() is giving you a full path to gem -- evidently /usr/bin/gem -- on the master. Since the whole point is that different servers have gem installed in different places, this is unhelpful. The actual error message arises from an attempt to execute your onlyif command with the wrong path to gem.
Your best way forward is probably to create a custom fact with which each node can report the appropriate location of the gem binary. You can then use that fact's value in your Exec, maybe:
exec { "remove-remote_syslog":
command => "$::ruby_gem_path uninstall remote_syslog",
onlyif => "$::ruby_gem_path list | grep remote_syslog"
}
Note that you don't need a path attribute if you give a complete path to the executable in the first place.
Details on creating the $::ruby_gem_path custom fact depend on a number of factors, and in their full generality they are rather too broad for SO, but PL provides good documentation.

Padrino Tutorial: Can't Modify Frozen String (Runtime Error)

I am following the Padrino tutorial from here:
https://www.padrinorb.com/guides/blog-tutorial
I am copy and pasting the commands but I quickly ran into an error I don't understand:
$ padrino g controller posts get:index get:show
create app/controllers/posts.rb
create app/views/posts
apply tests/shoulda
/Users/waprin/.rvm/gems/ruby-2.1.0/gems/padrino-gen-0.12.4/lib/padrino-gen/generators/controller.rb:66:in `prepend': can't modify frozen String (RuntimeError)
from /Users/waprin/.rvm/gems/ruby-2.1.0/gems/padrino-gen-0.12.4/lib/padrino-gen/generators/controller.rb:66:in `create_controller'
This might be a bit late, but in case anyone else runs across this error (and because I just worked through the same tutorial) I'll post anyway...
It looks like there's an issue when generating controllers if a test component is specified. In this case you're using shoulda, but the same happens when using rspec and maybe others. It's been reported as a bug: https://github.com/padrino/padrino-framework/issues/1850 and has been fixed, but isn't yet part of a stable release.
One option to fix this would be to change your Gemfile to work with the latest from their github repo. To do this delete your GemFile.lock file, and comment out the line under 'Padrino Stable Gem' in your GemFile:
gem 'padrino', '0.12.4'
then uncomment the line under 'Or Padrino Edge':
gem 'padrino', :github => 'padrino/padrino-framework'
then re-run bundle install.
Of course, you'll no longer be running the stable release, and that may come with other trade-offs.
As a side-note, I believe that the guide on that page is fairly out of date. I also needed to replace:
get :index do
#posts = Post.all(:order => 'created_at desc')
render 'posts/index'
end
with:
get :index, :provides => [:html, :rss, :atom] do
#posts = Post.order('created_at desc')
render 'posts/index'
end
in the Post controller as the active record interface has changed since the time that the guide was written.
I was able to sole this problem by simply going to padrino gem path.
For me it was:
/Users/ahmadhassan/.rvm/gems/ruby-2.2.0/gems/padrino-gen-0.12.4/lib/padrino-gen/generators
open controller.rb and change line number 61:
path = #controller
to
path = #controller.dup

Setting up rake-pipeline for use with handlebars alongside Google App Engine

So here's what I'm attempting to do. I'm building an ember.js application, with a java backend running on GAE.
I'm using handlebars, but I want them divided up into separate files, not just all pasted into the index.html.
Via the ember.js irc I was turned on to rake-pipeline along with minispade
Along with the web filters and a custom handlebars filter I started building the assetfile. I don't know Ruby, or gem files, etc.
So I'm trying to figure out the best way to be able to compile my coffeescript/handlebars files on the fly, minispade them, but keep the individual files accessible while in dev mode so I can debug them. What makes that hard is that the rake pipeline is running on a different port than GAE. So I'm not sure exactly how to handle this. Do I make my index file in GAE point to individual files at the 9292 port (rakep) during development, but in production mode point to the fully concatenated version? I'm not sure.
So I was attempting to do that here: https://gist.github.com/1495740 by having only one section that was triggered by the 'build' flag. Not even sure if that works that way.
I know there's a lot of confusion here. Apologies, like I said I'm not even remotely familiar with the Ruby style of doing things.
Since you're not a Ruby person, here are the most reliable steps for getting a stock OSX environment set up with rake pipeline:
Step 1: Install bundler
# on OSX, using built-in Ruby
$ sudo gem install bundler --pre
Step 2: Create a Gemfile
# inside your app directory
$ bundle init
# will create a file named Gemfile in the root
Step 3: Add rake-pipeline to the Gemfile
# inside the Gemfile
gem "rake-pipeline-web-filters"
Step 4: Install your gems
$ bundle install --binstubs
Step 5: Set up Assetfile
However you were already doing it...
Step 6: Run Rake::Pipeline
# to run the preview server
$ bin/rakep
# to build your assets
$ bin/rakep build
Rake::Pipeline.build is the method that evaluates an Assetfile. You can imagine that your entire Assetfile is wrapped inside a Rake::Pipeline.build {} block; you shouldn't ever need to write one inside an Assetfile.
Some of the filters in the docs are hypothetical, most of those docs were written before there were any filters at all. A CoffeeScript compiler has been recently added, though.
As to your main question, I'm not sure there's a clean way to do it with the current rakep implementation. An Assetfile is just Ruby, though, so it's possible to hack something together that should work. Here's how I would write yours:
require "json"
require "rake-pipeline-web-filters"
require "rake-pipeline-web-filters/helpers"
class HandlebarsFilter < Rake::Pipeline::Filter
def initialize(&block)
block ||= proc { |input| input.sub(/\.handlebars$/, '.js') }
super(&block)
end
def generate_output(inputs, output)
inputs.each do |input|
output.write "return Ember.Handlebars.compile(#{input.read.to_json})"
end
end
end
# process all js, css and html files in app/assets
input "assets"
# processed files should be outputted to public
output "public"
# process all coffee files
match "**/*.coffee" do
# compile all CoffeeScript files. the output file
# for the compilation should be the input name
# with the .coffee extension replaced with .js
coffee_script
# The coffee_script helper is exactly equivalent to:
# filter Rake::Pipeline::Web::Filters::CoffeeScriptCompiler
end
match "**/*.js" do
minispade
if ENV['RAKEP_ENV'] == "production"
concat "application.js"
else
concat
end
end
match "**/*.handlebars" do
filter HandlebarsFilter
minispade
concat "templates.js"
end
The if ENV['RAKEP_ENV'] bit reads an environment variable to decide whether to concatenate your JS to a single file.
So now you can run RAKEP_ENV="production" rakep build for a concatenated build, or just rakep build for a development build.

How can fixtures be replaced with factories using rails3-generators?

I'm trying to replace fixture generation with factories using rails3-generators:
https://github.com/indirect/rails3-generators#readme
The gem is included in my Gemfile and has been installed:
# Gemfile
gem 'rails3-generators', :group => :development
I added the following to application.rb:
# application.rb
config.generators do |g|
g.stylesheets false
g.fixture_replacement :factory_girl
end
Yet 'rails g model Insect' is still generating fixtures ('insects.yml'). Is this working for others using Rails 3.0.4 and rails3-generators 0.17.4?
'rails g' shows the new generators available (such as Authlogic and Koala), but 'rails g model' still lists fixtures and doesn't refer to factories.
What else should I add to get this to work? Thanks.
Edit: I ran the gem's test suite, which includes a test for this, and it passes. No clue why it doesn't work with my app.
Edit2: I tried again with a test project and get the same result: fixtures instead of factories. If anybody could confirm whether this works for them with Rails 3.0.4 and rails3-generators 0.17.4, that would be helpful too because it would imply that I'm doing something wrong with my projects.
Edit3: It works if I run 'rails g model Insect -r factory_girl'. I thought the generator configuration in application.rb was supposed to take care of that, so this seems to be the source of the problem.
Searching around I found the following, which may help:
Try specifying a directory option for factory_girl's factories:
config.generators do |g|
g.stylesheets false
g.fixture_replacement :factory_girl, :dir => "spec/factories" # or test/factories, as the case may be
end
If you're using Test::Unit, try the following:
config.generators do |g|
g.stylesheets false
g.test_framework :test_unit, :fixture_replacement => :factory_girl
end
In both cases you will still need the rails3-generators gem, although there is a push to get that functionality into factory_girl_rails.
This Rails bug indicates that, at some point, the g.fixture_replacement code may not have worked right. Perhaps a test in 3.0.5 is in order. :)
A short update 9 years later:
instead of "factory_girl_rails" (which is deprecated now) use "factory_bot_rails".
Now, the factory gets created automagically:
$ rails g model tester name:string
Running via Spring preloader in process 31467
invoke active_record
create db/migrate/20200327152901_create_testers.rb
create app/models/tester.rb
invoke rspec
create spec/models/tester_spec.rb
invoke factory_bot
create spec/factories/testers.rb
I use rails 5.2.4, but this should also work with rails 6.

Resources