Read Contents of a Local File into a Variable in Rails

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or function call. I revised it to open("/path/to/file", 'rb') {|io| a = a +} and all was fine.

Load file to rails console with access to variables defined in this file

When you load a file local variables go out of scope after the file is loaded that is why a and b will be unavailable in the console that loads it.

Since you are treating a and b as constants how about just capitalizing them like so

A = 1
B = 2
puts A+B

Now in you console you should be able to do the following

load 'myfile.rb'
A #=> 1

Alternately you could make the variables in myfile.rb global ($a, $b)

Accessing a variable declared in another rb file

The best way to export data from one file and make use of it in another is either a class or a module.

An example is:

# price.rb
module InstancePrices
'us-east-1' => {'t1.micro' => 0.02, ... },

In another file you can require this. Using load is incorrect.

require 'price'


You can even shorten this by using include:

require 'price'

include InstancePrices

What you've done is a bit difficult to use, though. A proper object-oriented design would encapsulate this data within some kind of class and then provide an interface to that. Exposing your data directly is counter to those principles.

For instance, you'd want a method InstancePrices.price_for('t1.micro', 'us-east-1') that would return the proper pricing. By separating the internal structure used to store the data from the interface you avoid creating huge dependencies within your application.

Accessing variables from included files in Ruby

You can't access a local outside of the scope it was defined in — the file in this case. If you want variables that cross file boundaries, make them anything but locals. $foo, Foo and @foo will all work.

If you just really don't want to put any sort of decoration on the symbol (because you don't like the way it reads, maybe), a common hack is just to define it as a method: def foo() "bar" end.

How do you access the raw content of a file uploaded with Paperclip / Ruby on Rails?

Here's how I access the raw contents of my attachment:

class Document

has_attached_file :revision

def revision_contents


Please note, I've omitted my paperclip configuration options and any sort of error handling.

Related Topics

Leave a reply