0

Still learning RoR, sometimes I'll see an example use of a library in plain Ruby that has require 'my_library'.

When we're in Ruby on Rails, are we able to do require? Or does everything have to be included in the gemfile (which I guess both installs and requires the library).

In particular I'm trying to call a API:

class MyModel < ActiveRecord::Base
    has_many :other_models

    def get_score
       require 'rest_client'
       response = RestClient.post 'https://sender.blockspring.com/api/blocks/da289f59df228ac4e89cebdfc9aa41fd?api_key=fe5cf0d86af27c086ab5cd4d0eab6641', { items_as_json_string: '[{"time_since_post_in_hours": 5, "upvote_count": 22}, {"time_since_post_in_hours": 3, "upvote_count": 502}]' }
    end
end
Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

1

require is part of Ruby and not unique to Rails. You can require stuff in Rails and it is normally done at the top of the Class and not inside of methods. require simply runs the file to make sure the functionality you are trying to use is loaded.

CWitty
  • 4,488
  • 3
  • 23
  • 40
1

You absolutely can require things, but you generally don't need to when they are declared in the Gemfile. One particular case where you'd need to require them is if you told it so, such as (in your Gemfile):

gem 'something_very_specific', require: false

Now, you'll need to require it in the "very specific" place you intended to use it.

Community
  • 1
  • 1
Nick Veys
  • 23,458
  • 4
  • 47
  • 64