uninitialized constant ActiveSupport::Json despite "require 'active_support/all'" - ruby-on-rails

I'm receiving a "uninitialized constant ActiveSupport::Json" error on the line where I call responseJson = ActiveSupport::Json.decode(response), in a small controller in my small Rails app.
The response variable returns a string with a response of the type {"token":"this_is_your_session_token"}.
I've added gem 'activesupport', '~> 4.2.3', to my Gemfile, tried different require statements with 'active_support/core_ext/object/json, and tried this in the IRB (with the same error). I'm not sure how to debug this further. Any help would be greatly appreciated.
require 'active_support/json'
require 'active_support'
require 'active_support/all'
require 'rest-client'
class WelcomeController < ApplicationController
def login_attempt
username = params[:u]
password = params[:p]
puts "waiting on request"
response = RestClient.post 'http://localhost:3001/v1/login', :email => username, :password => password
responseJson = ActiveSupport::Json.decode(response)
end
end

ActiveSupport::JSON (all caps). FYI, if you use pry instead of irb, you can run a command like 'ls ActiveSupport' and see the contained modules, methods, etc.

Related

Exception error="uninitialized constant V1" using Sneakers

I'm trying to implement Sneakers, but I'm having some issues. Below you can find the code which subscribers to my queue and the actual error.
require 'sneakers'
require 'jwt'
require 'redis'
require 'json'
$redis = Redis.new(url: ENV['REDIS_URL'], password: ENV['REDIS_PASSWORD'])
class Processor
include Sneakers::Worker
QUEUE_NAME = :my_queue
from_queue QUEUE_NAME
def work(msg)
message = JSON.parse(msg)
if message["type"] == "error"
$redis.incr "processor:#{err["error"]}"
end
controller = Object.const_get message['controller']
action = message['method']
controller.public_send(action, message['msg'])
ack!
end
end
Error:
[Exception error="uninitialized constant V1" error_class=NameError worker_class=Processor
The msg object
{\"controller\":\"V1::x::yController\",\"method\":\"my_method"\}
Any help is welcome, thank you!
Update
Even getting a simple Model such as my User is resulting into the same error.
[Exception error="uninitialized constant User"
I'm running the sneakers worker like so:
sneakers work UserCreate --require app/workers/user_create.rb

why am i getting "undefined method `strip' for nil:NilClass" when i'm not calling the strip method?

I'm building a rudimentary app using the Twilio API, and have reached a block when using figaro to store account_sid and auth_token as environment variables in application.yml.
In my controller I have:
require 'twilio-ruby'
require 'figaro'
class TwilioController < ApplicationController
def voice
account_sid = ENV["TWILIO_ACCOUNT_SID"]
auth_token = ENV["TWILIO_AUTH_TOKEN"]
#client = Twilio::REST::Client.new account_sid, auth_token
message = #client.account.sms.messages.create(:body => "Hello",
:to => "+12345678",
:from => "+12345678")
puts message.sid
end
end
And in config/application.yml I have:
# TWILIO_ACCOUNT_SID: 1234567890
# TWILIO_AUTH_TOKEN: 1234567890
The program works as intended when I replace the env variables with actual values, so the most I'm able to grasp at the moment is that something is preventing those variables from being set.
I just upgraded from Rails 4.2 to Rails 5 and started getting this error.
For me, it was because a newer HAML version was no longer tolerant of a pre-existing empty javascript block.
:javascript
I deleted the ':javascript' line and everything was fine afterwards.
move constants to development.rb
and then just:
account_sid = TWILIO_ACCOUNT_SID

Production uninitialized constant custom class stored in lib (heroku)

I have a custom class stored in /lib (/lib/buffer_app.rb):
require 'HTTParty'
class BufferApp
include HTTParty
base_uri 'https://api.bufferapp.com/1'
def initialize(token, id)
#token = token
#id = id
end
def create(text)
message_hash = {"text" => text, "profile_ids[]" => #id, "access_token" => #token}
response = BufferApp.post('/updates/create.json', :body => {"text" => text, "profile_ids[]" => #id, "access_token" => #token})
end
end
I'm attempting to use this this class in an Active Admin resource and get the following error when in production (Heroku):
NameError (uninitialized constant Admin::EventsController::BufferApp):
It's worth noting I have this line in my application.rb and that this functionality works locally in development:
config.autoload_paths += %W(#{Rails.root}/lib)
If I try include BufferApp or require 'BufferApp' that line itself causes an error. Am I having a namespace issue? Does this need to be a module? Or is it a simple configuration oversight?
I had exactly the same problem with Rails 5 alpha. To solve it, I had to manually require the file:
require 'buffer_app'
and not: (require 'BufferApp')
Even if Michal Szyndel's answer makes great sense to me, after manually requiring the file, prefixing :: to the constant was non influential in my case.
Anyway I am not satisfied with the manual requiring solution because I need to add code which is environment specific. Why don't I need to require the files manually in development?
Change this
config.autoload_paths += %W(#{Rails.root}/lib)
to this
config.eager_load_paths += %W(#{Rails.root}/lib)
eager_load_paths will get eagerly loaded in production and on-demand in development. Doing it this way, you don't need to require every file explicitly.
See more info on this answer.
Error line says it all, you should reference class as ::BufferApp

delayed_job gives "NameError: uninitialized constant"

I'm trying to move a current working task (in production and in the console) to use delayed_job in a Rails 2 app but keep getting the error:
ThermalImageJob failed with NameError: uninitialized constant Barby::Code128B
I've pored through others' code searching for an answer to no avail. Here's my code:
/lib/thermal_image_job.rb
class ThermalImageJob < Struct.new(:order_id)
def perform
order = Order.find(order_id)
order.tickets.each do |ticket|
ticket.barcodes.each do |barcode|
barcode.generate_thermal_image
end
end
end
end
/app/controllers/orders_controller.rb
Delayed::Job.enqueue(ThermalImageJob.new(#order.id))
/app/models/barcode.rb
def generate_thermal_image(format=:gif)
filename = "#{barcode}_thermal.#{format}"
temp_file_path = File.join("#{RAILS_ROOT}", 'tmp', filename)
unless FileTest.exists?(temp_file_path)
barcode_file = File.new(temp_file_path, 'w')
code = Barby::Code128B.new(barcode)
....
end
Gemfile
gem "delayed_job", "2.0.7"
gem "daemons", "1.0.10"
Well, after much head banging, I figured it out, so I'm posting this to help the next person. The problem was that it couldn't find the barby libs, so I added a require at the beginning of my class:
require "barby/outputter/rmagick_outputter"
require "barby/barcode/code_128"

Ruby/Rails - Cannot get size of array

I'm using the following code to scrape an eBay listing using the scrAPI gem:
I installed this by executing:
gem install scrapi
I'm also overriding its default text parser by declaring:
Scraper::Base.parser :html_parser
The problem is that I keep receiving the following error on the auctions array size. Not sure what I'm doing wrong? Both size and length don't work.
Scraper.rb:31:in `<class:ScraperDemo>': undefined method `size' for nil:NilClass (No
MethodError)Scraper.rb:10:in `<main>'
I just run via the commandline:
ruby Scraper.rb
Code:
#!/usr/bin/env ruby
require 'open-uri'
require 'httparty'
require 'json'
require 'scrapi'
Scraper::Base.parser :html_parser
class ScraperDemo
ebay_auction = Scraper.define do
process "h3.ens>a", :description=>:text, :url=>"#href"
process "td.ebcPr>span", :price=>:text
process "div.ebPicture >a>img", :image=>"#src"
result :description, :url, :price, :image
end
ebay = Scraper.define do
array :auctions
process "table.ebItemlist tr.single", :auctions=>ebay_auction
result :auctions
end
auctions = ebay.scrape(URI.parse('http://search.ebay.com/ipod-nano_W0QQcatrefZC6QQfromZR3QQfsooZ1QQfsopZ1QQkeywordZonQQsacatZQ2d1QQstrkwZipod'))
# No. of channels found
puts auctions.size # error occurs on this line number
# First auction:
auction = auctions[0]
puts auction.description
puts auction.url
end
I ended up using Nokogiri as my scraper of choice.

Resources