ActiveSupport overrides #to_json behavior - ruby-on-rails

How to teach ActiveSupport to not override standard "json" gem behavior?
require "rubygems"
gem "json"
require "json"
class Time
def to_json(options = nil)
"custom string"
end
end
hash = { :x => Time.now }
puts hash.to_json # => {"x":custom string}
gem "activesupport"
require "active_support/core_ext/object" # Somewhere into Rails internals
puts Time.now.to_json # => custom string
puts hash.to_json # => {"x":"2011-02-14T16:30:10+05:00"}
Expected: after require "active_support/core_ext/object" I wanna get {"x":custom string} result.

Rails since v2.3.3 switched to #as_json due to some significant reasons. So dance with it.
http://weblog.rubyonrails.org/2009/7/20/rails-2-3-3-touching-faster-json-bug-fixes

You have to define
class Time
def to_json(options = nil)
"custom string"
end
end
after
gem "activesupport"
require "active_support/core_ext/object"
code.

How about formatting your Time.now value with strftime like Time.now.strftime("format") for the formatting string please see the Ruby Docs.
Or if you don't really want to format it, just use it as a string call Time.now.to_s

Related

Save xlsx file to disk in Sidekiq as background

I am trying to generate excel file in background by using axlsx and save it (Rails4.2). In GitHub page of axlsx, it says As of Rails 4.1 you must use render_to_string to render a mail attachment. However, it throws me a error NoMethodError: undefined method 'render_to_string' for #<CreateExcelSheetWorker:0x007fbccf51db30>
My worker class:
class CreateExcelSheetWorker
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence { daily }
def perform()
model = SomeModel.where(wanted: true).order(started_at: :desc)
xlsx = render_to_string handlers: [:axlsx], formats: [:xlsx], template: "template/file", locals: {model: model}
path = "/tmp/a.xlsx"
File.open(path, "w+") do |f|
f.write(xlsx)
end
end
end
I cannot figure out how to fix this, any help appreciated.
That render_to_string comment is for usage of the gem in actionmailers. Outside of any kind of view context, you'll have to use xlsx builder api directly. Something like this:
package = Axlsx::Package.new do |p|
p.workbook.add_worksheet(name: "Summary") do |sheet|
sheet.add_row ["foo", 1]
end
end
File.write(filename, package.to_stream.read)
Sergio's answer is fine. But, if you are wanting to use the axlsx_rails template, you can use this example, which builds a fake view context to render the template:
require 'abstract_controller'
require 'action_controller'
require 'action_view'
require 'active_record'
# require any helpers
require './app/helpers/application_helper'
# active record only if data is here
require './app/models/widget'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: 'db/development.sqlite3'
)
ActionController::Base.prepend_view_path "./app/views/"
# place data in view_assigns
view_assigns = {widgets: Widget.all}
av = ActionView::Base.new(ActionController::Base.view_paths, view_assigns)
av.class_eval do
# include any needed helpers (for the view)
include ApplicationHelper
end
# normal render statement
content = av.render template: 'widgets/index.xlsx.axlsx'
# do something with content, such as:
File.open("/tmp/with_runner.xlsx","w+b") {|f| f.puts content }
https://gist.github.com/straydogstudio/dceb775ead81470cea70

uninitialized constant ActiveSupport::Json despite "require 'active_support/all'"

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.

I want to split JavaScript multidimesional array in ruby which is get through ajax in rails

Here Is my string I want to convert it in to ruby multidimesinal array
"[[43.632526509656685,-79.42367434501648],[43.64327275111337,-79.37912821769714],[43.66038201798689,-79.36055123806],[43.64675865498884,-79.40652161836624],[43.66742924566789,-79.38179969787598],[43.63811727974008,-79.38262581825256],[43.65475450763126,-79.38058733940125],[43.80799100738646,-79.29940223693848],[43.645477667051665,-79.39501762390137],[43.659112963434545,-79.36607658863068],[43.90563829766256,-78.95808577537537],[43.65835617501699,-79.40053224563599],[43.65275952562007,-79.38706755638123],[43.64162677519443,-79.42197382450104],[43.71039321515471,-79.63683485984802],[43.654537158722405,-79.38046932220459],[43.63306231432476,-79.41863179206848],[43.67294692682542,-79.37639236450195],[43.65419560884771,-79.37847375869751],[43.65715305584598,-79.35915112495422],[43.67200018777028,-79.3865954875946],[43.84799142017673,-78.9451253414154],[43.68109447341254,-79.39103722572327],[43.63182762682362,-79.39525365829468],[43.84737242300824,-79.38278675079346],[43.75090070490045,-79.41256999969482],[43.65947777085417,-79.40065562725067],[43.59501608244168,-79.63583707809448],[43.63299242703026,-79.41939353942871],[43.70515819193044,-79.31272745132446],[43.52992910375604,-79.65393662452698],[43.68891507733449,-80.48693418502808],[43.64301654084419,-79.33723211288452],[43.72113327572119,-79.33848738670349],[43.667258507639936,-79.40012454986572],[43.678696881723354,-79.34523314237595],[43.45344850846621,-79.69355821609497],[43.65345040237827,-79.3847930431366],[43.3642365466385,-79.7905683517456],[43.82110555105607,-79.18692111968994],[43.64348237688449,-79.3785810470581],[43.76942035754388,-79.36247706413269],[43.69990719828152,-79.45181608200073],[43.64671207408792,-79.39049005508423],[43.72798729713697,-79.54898715019226],[43.67445430634414,-79.29921716451645],[43.754651591176284,-79.35048222541809],[43.67627591523589,-79.35731649398804],[43.6542809964985,-79.42377090454102],[43.650430669010696,-79.35830354690552],[43.66928405022088,-79.33582663536072],[43.474921264411634,-79.67675149440765],[43.68361610886464,-79.39244270324707],[43.677067395795895,-79.35306787490845],[43.64453825853618,-79.41219449043274],[43.65700557506316,-79.37058806419373],[43.796236566933004,-79.19906616210938],[43.646890634011946,-79.38621997833252],[43.660428588285924,-79.43207502365112],[43.65251888128742,-79.4332230091095],[43.6519289104566,-79.40836429595947],[43.663812599997385,-79.37043249607086],[43.66875244891782,-79.3839830160141],[43.67026963434066,-79.38314080238342],[43.74442134761432,-79.2999655008316],[43.64619968179377,-79.38820481300354],[43.65590333879542,-79.4527280330658],[43.68945813696888,-79.74513173103333],[43.65217731993387,-79.37948226928711],[43.67876671584565,-79.40820336341858],[43.899152522512765,-79.39220666885376],[43.69577278368514,-79.26072478294373],[43.63165678756161,-79.39611196517944],[43.66720418180192,-79.34528946876526],[43.6545682086147,-79.42075610160828],[43.64206156566899,-79.43235397338867],[43.67598880696224,-79.40114378929138],[43.65065579575911,-79.39661622047424],[44.65809174295625,-63.67159724235535],[43.6643791704723,-79.39823627471924],[43.661165946540024,-79.36493396759033],[43.65983093337226,-79.36318516731262],[43.66877961114232,-79.39261436462402],[43.644336400243496,-79.39957737922668],[43.657882692284524,-79.40149784088135],[43.734274629307684,-79.35824990272522],[43.65214626880541,-79.37957882881165],[43.70406847405242,-79.37469184398651],[43.64380069610123,-79.38694953918457],[43.671736339798734,-79.38689589500427],[43.65152524286464,-79.39788222312927],[43.665007824604,-79.39396619796753],[43.67191482531818,-79.38711047172546],[43.66546572902495,-79.39987778663635],[43.71618610788623,-79.37770128250122],[43.69311978214946,-79.51615691184998],[43.65280027980674,-79.36274260282516],[43.64487986333245,-79.39537167549133],[43.59088221282021,-79.51367855072021],[43.64330380682931,-79.37867760658264],[43.70922991617265,-79.65058922767639],[43.656656277027395,-79.38060879707336],[43.63137723135809,-79.39621925354004],[43.66494961616467,-79.43715512752533],[43.656532081680574,-79.3738067150116],[43.71834957479718,-79.32960391044617],[43.67747865118097,-79.62430357933044],[43.714790281327886,-79.58611965179443],[44.13428203149913,-79.31930422782898],[44.84029065139799,-80.859375]]"
I should get as multi dimension array in ruby
You need to use YAML stdlib:
require 'yaml'
a = "[[43.632526509656685,-79.42367434501648],[43.64327275111337,-79.37912821769714]]"
YAML.load(a)
# => [[43.632526509656685, -79.42367434501648],
# [43.64327275111337, -79.37912821769714]]
or use JSON stdlib.
require 'json'
a = "[[43.632526509656685,-79.42367434501648],[43.64327275111337,-79.37912821769714]]"
JSON.parse(a)
# => [[43.632526509656685, -79.42367434501648],
# [43.64327275111337, -79.37912821769714]]
Use JSON.parse:
require 'json'
JSON.parse("[[43.632526509656685,-79.42367434501648], [43.64327275111337,-79.37912821769714]]")
# => [[43.632526509656685, -79.42367434501648],
# [43.64327275111337, -79.37912821769714]]

Ruby - undefined method `extract_options!' : Array

While running following sample using TweetStream I am getting mentioned error.
tweets.rb
require 'tweetstream'
TweetStream.configure do |config|
config.consumer_key = '<CONSUMER KEY>'
config.consumer_secret = '<CONSUMER SECRET>'
config.oauth_token = '<OAUTH TOKEN>'
config.oauth_token_secret = '<OAUTH TOKEN SECRET'
config.auth_method = :oauth
end
TweetStream::Client.new.track('ruby') do |status|
puts "#{status.text}"
end
Error
$ ruby tweets.rb
/home/amit/.rvm/gems/ruby-1.9.3-p194/gems/tweetstream-2.3.0/lib/tweetstream/client.rb:96:in `track': undefined method `extract_options!' for ["ruby"]:Array (NoMethodError)
from tweets.rb:11:in `<main>'
https://github.com/intridea/tweetstream
Am I missing something?
Here's another solution: opening up Array class and defining extract_options! method on it.
Add the following code :
class Array
def extract_options!
last.is_a?(::Hash) ? pop : {}
end unless defined? Array.new.extract_options!
end
to the beginning of the tweets.rb file or to a separate file (which would
need to be required in the tweets.rb file).
extract_options! is ActiveSupport method. If it's not rails app you need to install it and include into script.
I am too late to answer but i think it'll be useful for ruby naive programmers like me.
To include ActiveSupport method like extract_options!, you need to include Active Support.
require 'active_support'
And if you want to include ruby gems then include rubygems too.
require 'rubygems'

ActionMailer and Ramaze

Is it possible to use ActionMailer in a web framework like Ramaze, or do I need to use Rails?
You can use ActionMailer without Rails quite easily. I'm not familiar with Ramaze, but here's plain ruby, which should be easy to integrate into whatever framework you wish:
PATH/mailer.rb
require 'rubygems'
require 'action_mailer'
class Mailer < ActionMailer::Base
def my_email
recipients "recipient#their_domain.com"
from "me#my_domain.com"
subject "my subject"
body :variable1 => 'a', :variable2 => 'b'
end
end
Mailer.template_root = File.dirname(__FILE__)
Mailer.delivery_method = :sendmail
Mailer.logger = Logger.new(STDOUT)
# this sends the email
Mailer.deliver_my_email
Then put the email templates in a directory named after the your ActionMailer class
PATH/mailer/my_email.html.erb
variable 1: <%= #variable1 %>
variable 2: <%= #variable2 %>
Check out the API Docs for more configuration options, but those are the basics

Resources