How to read files (.yml) from a Gem - ruby-on-rails

I want to read a .yml file included in a Rails Engine Gem from my main_app. The file is located at config/test.yml.
IO.read("config/test.yml") fails with No such file or directory # rb_sysopen
If i move the file into the main app, everything works fine. But i need this file in a Gem.

Solution 1
You can store the root path in a constant from your main gem file and retrieve it in other locations of your code. You must ensure that the gem got initialized before the code in your app runs otherwise you'll have an errors because the constant won't be defined.
# lib/my_gem.rb
GEM_ROOT = File.expand_path("../..", __FILE__)
# app/.../some_class.rb
IO.read("#{GEM_ROOT}/config/test.yml")
Solution 2
The most advisable, you can get the gem path programmatically from Bundler, then use that root path to retrieve the full path of your yml file.
Have a look at this answer that you can easily adapt to your case

You should be able to load app yaml files by doing this in your gem:
YAML.load_file('config/test.yml')

Related

Can I use shared gem in rails directory?

I want to use one gem installed in system directory at a Rails project.For a certain reason, I cannnot add it to Gemfile and bundle install.Basicaly, I use bundler.
I want to do like this,
require 'gem_installed_in_vendor/bundle'
require 'gem_installed_in_system'
I wonder removing disable_shared_gems option help my hope,and I delete it from .bundle/config.But,it doens't work hopely.
output of bundle config is,
Settings are listed in order of priority. The top value will be used.
path
Set for your local app (/Users/my_name/works/thisApp/.bundle/config): "vendor/bundle"
and which gem's output is,
/Users/my_name/.rbenv/shims/gem

Remove bootstrap media queries from rails app

Is there a way to remove just the boostrap media queries in my Rails app? I am unable to find the bootstrap.css file.
The bootstrap styles are located in the gem installation directory. You can find this directory by issuing the following command in your terminal and look for GEM_PATH:
gem env
Another way to find the gem path is by issuing
bundle show bootstrap
which will include the path of the gem installation.
Once you've located the path, copy the directory bootstrap from GEM_PATH/vendor/assets/stylesheets/ to your app/assets/stylesheets directory. I think the file you want to look at is app/assets/bootstrap/responsive.scss, at least this is where you want to start. Depending upon what you want to modify, modify the the content of this file.

How to require a gem in .irbrc without needing to also add it to a Rails Gemfile?

I've added awesome_print to my ~/.irbrc file like so:
require 'ap'
Inside a Rails project directory, if I run irb it loads the gem fine, because I've already installed the gem locally. But if I run rails console, it spits out this error:
cannot load such file -- ap
How can I resolve this? I am guessing that it's looking for the gem in the app's Gemfile, but I don't want to add it to the Gemfile because I don't want other developers requiring that dependency. I only want to use awesome_print on my machine.
I am also using rbenv, if that is of any help.
There is this trick.
What you need to do is
# Copy the definition of the debundle! method into your ~/.irbrc
# Call 'debundle!' from IRB when you need to.
(as explained at the top of the file)
The text as it appears on the referred to site:
debundle.rb allows you to require gems that are not in your Gemfile when inspecting
programs that are run with Bundler.
Use at your own risk!
Paste the code of debundle.rb and you are done! A good place would be your .irbrc file
before requiring irbtools.
The code is directly taken from pry-debundle.
Please look there for any further information. This repo exists to simplify debundling
without using the pry repl.

How does load differ from require in Ruby?

Is there any major difference between load and require in the Ruby on Rails applications? Or do they both have the same functionality?
require searches for the library in all the defined search paths and also appends
.rb or .so to the file name you enter. It also makes sure that a library is only
included once. So if your application requires library A and B and library B requries library A too A would be loaded only once.
With load you need to add the full name of the library and it gets loaded every time you
call load - even if it already is in memory.
Another difference between Kernel#require and Kernel#load is that Kernel#load takes an optional second argument that allows you to wrap the loaded code into an anonymous empty module.
Unfortunately, it's not very useful. First, it's easy for the loaded code to break out of the module, by just accessing the global namespace, i.e. they still can monkeypatch something like class ::String; def foo; end end. And second, load doesn't return the module it wraps the code into, so you basically have to fish it out of ObjectSpace::each_object(Module) by hand.
I was running a Rails application and in Gemfile, I had a specific custom gem I created with the option "require: false". Now when I loaded up rails server or rails console, I was able to require the gem in the initializer and the gem was loaded. However, when I ran a spec feature test with rspec and capybara, I got a load error. And I was completely bewildered why the Gem was not found in $LOAD_PATH when running a test.
So I reviewed all the different ways that load, require, rubygems and bundler interact. And these are a summary of my findings that helped me discover the solution to my particular problem:
load
1) You can pass it an absolute path to a ruby file and it will execute the code in that file.
load('/Users/myuser/foo.rb')
2) You can pass a relative path to load. If you are in same directory as file, it will find it:
> load('./foo.rb')
foo.rb loaded!
=> true
But if you try to load a file from different directory with load(), it will not find it with a relative path based on current working directory (e.g. ./):
> load('./foo.rb')
LoadError: cannot load such file -- foo.rb
3) As shown above, load always returns true (if the file could not be loaded it raises a LoadError).
4) Global variables, classes, constants and methods are all imported, but not local variables.
5) Calling load twice on the same file will execute the code in that file twice. If the specified file defines a constant, it will define that constant twice, which produces a warning.
6) $LOAD_PATH is an array of absolute paths. If you pass load just a file name, it will loop through $LOAD_PATH and search for the file in each directory.
> $LOAD_PATH.push("/Users/myuser")
> load('foo.rb')
foo.rb loaded!
=> true
require
1) Calling require on the same file twice will only execute it once. It’s also smart enough not to load the same file twice if you refer to it once with a relative path and once with an absolute path.
2) require returns true if the file was executed and false if it wasn’t.
3) require keeps track of which files have been loaded already in the global variable $LOADED_FEATURES.
4) You don’t need to include the file extension:
require 'foo'
5) require will look for foo.rb, but also dynamic library files, like foo.so, foo.o, or foo.dll. This is how you can call C code from ruby.
6) require does not check the current directory, since the current directory is by default not in $LOAD_PATH.
7) require_relative takes a path relative to the current file, not the working directory of the process.
Rubygems
1) Rubygems is a package manager designed to easily manage the installation of Ruby libraries called gems.
2) It packages its content as a zip file containing a bunch of ruby files and/or dynamic library files that can be imported by your code, along with some metadata.
3) Rubygems replaces the default require method with its own version. That version will look through your installed gems in addition to the directories in $LOAD_PATH. If Rubygems finds the file in your gems, it will add that gem to your $LOAD_PATH.
4) The gem install command figures out all of the dependencies of a gem and installs them. In fact, it installs all of a gem’s dependencies before it installs the gem itself.
Bundler
1) Bundler lets you specify all the gems your project needs, and optionally what versions of those gems. Then the bundle command installs all those gems and their dependencies.
2) You specify which gems you need in a file called Gemfile.
3) The bundle command also installs all the gems listed in Gemfile.lock at the specific versions listed.
4) Putting bundle exec before a command, e.g. bundle exec rspec, ensures that require will load the version of a gem specified in your Gemfile.lock.
Rails and Bundler
1) In config/boot.rb, require 'bundler/setup' is run. Bundler makes sure that Ruby can find all of the gems in the Gemfile (and all of their dependencies). require 'bundler/setup' will automatically discover your Gemfile, and make all of the gems in your Gemfile available to Ruby (in technical terms, it puts the gems “on the load path”). You can think of it as an adding some extra powers to require 'rubygems'.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
2) Now that your code is available to Ruby, you can require the gems that you need. For instance, you can require 'sinatra'. If you have a lot of dependencies, you might want to say “require all of the gems in my Gemfile”. To do this, put the following code immediately following require 'bundler/setup':
Bundler.require(:default)
3) By default, calling Bundler.require will require each gem in your Gemfile. If the line in the Gemfile says gem 'foo', :require => false then it will make sure foo is installed, but it won’t call require. You’ll have to call require('foo') if you want to use the gem.
So given this breadth of knowledge, I returned to the issue of my test and realized I had to explicitly require the gem in rails_helper.rb, since Bundler.setup added it to $LOAD_PATH but require: false precluded Bundler.require from requiring it explicitly. And then the issue was resolved.

How can I modify Rails' config within an engine plugin?

I'm working on an engine for Rails as a plugin. I'd like it to be able to make necessary changes to Rails' configuration when it's loaded so it can specify its Gem dependencies as well as add some load paths.
The plugin's init.rb file has access to the config object but this is effectively read-only, you can specify a gem but it makes no difference, the initializer must have run already at this point.
I've got around this for now by requiring a file with a new Rails::Initializer block like so:
Rails::Initializer.run do |config|
config.gem "authlogic", :version => ">= 2.0.9"
# etc
end
This works but wipes out any existing configuration in the main application's environment.rb.
Maybe I can solve this by having a generator in the engine that adds something to environment.rb that loads the plugin's config at the right stage, or maybe there is a way of adding a file to config/initializers to do this job. Not sure how best to go about this though.
I would go with the config/initializers route. That is the standard folder to put plugin-specific config code and it will get loaded at the correct time.
For implementation, I would try my hardest to choose sensible defaults for everything that allowed me to not have a config file. (I understand this is not always possible.)
Next I would create a generator with the plugin that would automatically create the config file in config/initializers using:
./script/generate plugin MyPlugin --with-generator
Finally, I would put something in install.rb of my plugin to run the generator script when the plugin is installed. This way the config file is generated automatically with the install, and the user still has an easy way to regenerate if he wants to restore the default configuration.
Are you sure you want to distribute this as a plugin rather than a gem? If you package your engine as a gem then you can specify gem dependencies as part of your gem build process. For example, if you use Jeweler to create your gem you just add a single line:
s.add_dependency 'authlogic'
When your gem is installed it will make sure all dependencies are installed. Google 'jeweler gem dependency' for a full Jeweler config example.
Also, I've been doing a lot of work on my own rails engine and recently extracted a lot of useful base functionality. You may find this helpful for other engine issues:
http://keithschacht.com/creating-a-rails-3-engine-plugin-gem/
You can easily add this line to init.rb (under your plugin directory)
config.gem 'quick_magick'
I tried it with rails 2.3.5 and it worked like magic.

Resources