I'm using Barby to generate EAN13 Barcodes.
I'm getting the error: undefined method two_dimensional?' for "400000000000":String
The code i'm using in the controller:
def index
#barcode = getnumber
#barcode_voorbeeld = Barby::HtmlOutputter.new(#barcode)
#barcode_voorbeeld.to_html
end
def getnumber
Barcode.first.number
end
In the end what I want to accomplish is to get the last Barcode model and add + 1 to the number, so something like #barcode = getnumber + "1" and the result of this should be in this case 400000000001
thanks in advance.
#number = getnumber
#barcode = Barby::Code128B.new(#number)
#barcode_voorbeeld = Barby::HtmlOutputter.new(#barcode)
#barcode_voorbeeld.to_html
Related
I have a method CustomGoogleDirections
class CustomGoogleDirections < GoogleDirections
##base_url = "https://maps.googleapis.com/maps/api/directions/xml"
end
Which i call in my controller to find the location based on a hash:
#locations = #all_locations.each_cons(2).with_index.with_object({}) do |((e1, e2), i), h|
h[i + 1] =
[e1, e2,
CustomGoogleDirections.new(e1, e2, key: Figaro.env.google_translate_secret_key).distance_in_miles, CustomGoogleDirections.new(e1, e2, key: Figaro.env.google_translate_secret_key).drive_time_in_minutes.url]
end
This result in the error:
Errno::ENOENT (No such file or directory # rb_sysopen - https://maps.googleapis.com/maps/api/directions/xml?destination=60%2BBarron%2BRoad%252C%2BDubai%252C%2BDubai&key=######################&origin=60%2BAlFhaged%2BRoad%252C%2BDubai%252C%2Dubai)
It used to work well before I did a rails upgrade.
Does anynone knows what I am missing please?
(When I used the generated xml link, it does load properly with all the long/lat informations)
I found a solution by modifying the gem, changing :
#url = ##base_url + '?' + #options.to_query
#xml = open(#url).read
#doc = Nokogiri::XML(#xml)
#status = #doc.css('status').text
to :
#url = ##base_url + '?' + #options.to_query
#response = Net::HTTP.get_response(URI(#url))
#doc = Nokogiri::XML(#response.body)
#status = #doc.css('status').text
It works locally but not sure about this as the right approach.
I've got a bar graph that I'm trying to populate with a JSON response. I'm using Rails 5 with the built in JBuilder functionality.
Here is my code:
def graph_data
#customers = Customer.all
#graph_data = {graph_type: "Customer Growth"}
#months = {}
x = 5
while x >= 0
#months[x.months.ago.strftime("%B")] = current_account.customers.where(:created_at => x.months.ago.beginning_of_month..x.months.ago.end_of_month).count
x = x - 1
end
#graph_data[:months] = #months
puts #graph_data.to_json
end
The line puts #graph_data.to_json outputs the following text:
{"graph_type":"Customer Growth","months":{"November":0,"December":0,"January":0,"February":0,"March":0,"April":3}}
as I would expect.
However, when I output the actual JSON response in my graph_data.json.jbuilder file the output is
[["graph_type","Customer Growth"],["months",{"November":0,"December":0,"January":0,"February":0,"March":0,"April":3}]]
My goal was to get a response that looked more like this:
{"graph_type":"Customer Growth","months":["November":0,"December":0,"January":0,"February":0,"March":0,"April":3]}
but I don't know how to accomplish this with jBuilder.
Here are the contents of my graph_data.json.jbuilder file.
json.array! #graph_data
Thanks in advance.
In your jbuilder file, replace
json.array! #graph_data
to
json.graph_type #graph_data[:graph_type]
json.months #graph_data[:months]
Going blind here.. I can't understand why these 2 strings are not equal.. When I puts them to the terminal they are both class string and when I just compare the output they ARE equal. But somehow in my code they are not.. I can't figure out why.
Here is my Ruby code:
def prep_for_duplicate_webhook
#redis_cart = Redis.new
cart_stamp_saved = #redis_cart.get("cart_stamp_saved")
if cart_stamp_saved.nil?
cart_stamp_saved = {}
cart_stamp_saved[:token] = cart_params['token']
cart_stamp_saved[:updated_at] = cart_params['updated_at']
#redis_cart.set("cart_stamp_saved", cart_stamp_saved.to_json)
end
#cart_stamp_incoming = {}
#cart_stamp_incoming["token"] = cart_params['token']
#cart_stamp_incoming["updated_at"] = cart_params['updated_at']
end
def duplicate_webhook?
prep_for_duplicate_webhook
#cart_stamp_saved = redis_cart.get("cart_stamp_saved")
cart_stamp_saved == cart_stamp_incoming.to_json
end
And then the hash's I'm comparing are these two:
cart_stamp_saved = {"token"=>"4a093432ba5c430dd545b16c0e89f187",
"updated_at"=>"2017-02-17T15:27:22.923Z"}
cart_stamp_incoming= {"token"=>"4a093432ba5c430dd545b16c0e89f187",
"updated_at"=>"2017-02-17T15:27:22.923Z"}
If I just copy and paste the above into a new page, and the do this, the response is true
pp cart_stamp_saved == cart_stamp_incoming.to_json
What am I missing?
I'm trying to generate stats for a character created by a form. The user inputs the name, race, class, alignment, and whether or not the stats will be generated randomly, or prioritized (values being assigned from highest to lowest). The form works flawlessly, as I can see the output in a view.
What I am now trying to do is call a method from a class in /lib in the model that will generate the stats; however, I keep getting the following error (I can't post pictures):
NoMethodError in CharactersController#create
undefined method `[]' for nil:NilClass
Extracted source (around line #14):
12 before_save do
13 generate_stats
14 self.strength = #character_stats[:strength]
15 self.dexterity = #character_stats[:dexterity]
16 self.constitution = #character_stats[:constitution]
17 self.intelligence = #character_stats[:intelligence]
Here is a copy of some of my code:
In controllers\characters_controller.rb
class CharactersController < ApplicationController
def create
#character = Character.new(character_info_params)
#character.name = params[:character][:name].capitalize
#character.alignment = "#{params[:character][:alignment_lr]} #{params[:character][:alignment_ud]}"
if #character.save
redirect_to #character
else
render 'new'
end
end
private
def character_info_params
params.require(:character).permit(:name, :race, :class_, :alignment)
end
end
In models\character.rb
class Character < ActiveRecord::Base
require 'random_stats_generator'
attr_accessor :rand_stat_gen
def generate_stats
if #rand_stat_gen == true
#character_stats_inst = RandomStatGenerator.new
#character_stats = #character_stats_inst.generate
end
end
before_save do
generate_stats
self.strength = #character_stats[:strength]
self.dexterity = #character_stats[:dexterity]
self.constitution = #character_stats[:constitution]
self.intelligence = #character_stats[:intelligence]
self.wisdom = #character_stats[:wisdom]
self.charisma = #character_stats[:charisma]
end
#validation passed this point
end
In initializers\stat_builders.rb
require "./lib/random_stat_generator.rb"
In lib/random_stat_generator.rb
class RandomStatGenerator
def initialize
#strength = :strength
#dexterity = :dexterity
#constitution = :constitution
#intelligence = :intelligence
#wisdom = :wisdom
#charisma = :charisma
#character_stats = HashWithIndifferentAccess.new()
end
def self.generate
roll_stats
end
def roll(stat)
#roll_value_1 = (1 + (rand(6)))
#roll_value_2 = (1 + (rand(6)))
#roll_value_3 = (1 + (rand(6)))
#roll_value_4 = (1 + (rand(6)))
#roll_array = [#roll_value_1,#roll_value_2,#roll_value_3,#roll_value_4]
#roll_array = #roll_array.sort_by {|x| x }
#roll_array = #roll_array.reverse
stat = #roll_array[0] + #roll_array[1] + #roll_array[2]
end
def roll_stats
#strength = roll(#strength)
#dexterity = roll(#dexterity)
#constitution = roll(#constitution)
#intelligence = roll(#intelligence)
#wisdom = roll(#wisdom)
#charisma = roll(#charisma)
#character_stats[:strength] = #strength
#character_stats[:dexterity] = #dexterity
#character_stats[:constitution] = #constitution
#character_stats[:intelligence] = #intelligence
#character_stats[:wisdom] = #wisdom
#character_stats[:charisma] = #charisma
return #character_stats
end
end
To me, it looks like the method isn't returning anything, or isn't being called at all.
I've tried a lot of solutions that I've come across online, none of them working. There may be some things that don't really make sense that are left over from these solutions. I'm only just starting with rails, so I'm still trying to get used to everything.
Thanks a lot for your help.
Ruby has really powerful functions for manipulating both hashes and arrays.
Typing out duplicate assignments like:
self.strength = #character_stats[:strength]
self.dexterity = #character_stats[:dexterity]
self.constitution = #character_stats[:constitution]
Is pretty dull. So instead we can simply rewrite the methods to pass hashes around.
class RandomStatGenerator
# This is just a constant containing all the stats we want to generate.
STATS = [:strength, :dexterity, :constitution, :intelligence, :wisdom, :charisma]
# Create a hash with random roll values for each stat
def self.roll_stats
# This is kind of scary looking but actually just creates an
# hash from an array of keys
Hash[STATS.map {|k| [k, self.roll ] } ]
end
private
def self.roll
# Create an array with 4 elements (nil)
ary = Array.new(4)
# We then replace the nil value with a random value 1-6
ary = ary.map do
(1 + (rand(6)))
end
# sort it and drop the lowest roll. return the sum of all rolls.
ary.sort.drop(1).sum
# a ruby ninja writes it like this
Array.new(4).map { 1 + rand(6) }.sort.drop(1).sum
end
end
Output:
irb(main):032:0> RandomStatGenerator.roll_stats
=> {:strength=>14, :dexterity=>14, :constitution=>14, :intelligence=>13, :wisdom=>10, :charisma=>9}
But if you don't intend to actually create instances of a class, than you should use a module instead.
Rails models can either be created with a hash or you can replace its values with a hash:
Character.new(RandomStatGenerator.roll_stats)
#character.assign_attributes(RandomStatGenerator.roll_stats)
So we can use this in Character#generate_stats:
def generate_stats
assign_attributes(RandomStatGenerator.roll_stats)
end
You should use ActiveModel callbacks with extreme prejudice. It is often quite a challenge to regulate where in your application and when in the model lifetime. Since before_save runs after validations means that any validations like validates_presence_of :constitution will fail.
In your case it might be better to simply do it in the controller or use:
before_validation :generate_stats, if: -> { new_record? && #rand_stat_gen }
I would like to suggest the following organisation fo your library
# Use a module at top level
module RandomStatGenerator
STATS = [:strength, :dexterity, :constitution, :intelligence, :wisdom, :charisma]
# Use a class Stats if you need to but I don't see why...
class Stats
def initialize
RandomStatGenerator::STATS.each do |stat|
# Below line will do #stat = :stat
instance_variable_set("##{stat.to_s}", stat)
#character_stats = HashWithIndifferentAccess.new()
end
def roll_stats
#character_stats = RandomStatGenerator.roll_stats
end
end
module_function
# below lines will be considered as module functions
# => call RandomStatGenerator.function_name
def roll
roll_value_1 = (1 + (rand(6)))
roll_value_2 = (1 + (rand(6)))
roll_value_3 = (1 + (rand(6)))
roll_value_4 = (1 + (rand(6)))
roll_array = [roll_value_1,roll_value_2,roll_value_3,roll_value_4]
roll_array = roll_array.sort_by {|x| x }
roll_array = roll_array.reverse
roll_array[0] + roll_array[1] + roll_array[2]
end
def roll_stats
character_stats = {}
STATS.each do |stat|
character_stats[stat] = RandomStatGenerator.roll
end
return character_stats
end
end
Then in your character.rb
def generate_stats
#character_stats = RandomStatGenerator.roll_stats
end
I have the following controller method
def app_used_by_Lab
per_id = params[:id]
#search1 = Apparatus.used_by_specific_lab(per_id).search(params[:search]) # both 'used_by_specific_lab' & 'lab_created' are named_scopes which return results from the same table
#search2 = Apparatus.lab_created(per_id).search(params[:search])
#search = #search2 + #search1
#search.order ||= :descend_by_RPR_DATE_CREATED
#apparatuses = #search.paginate(:page => params[:page], :per_page => 10)
end
If I change the code to '#search = #search1', it works fine and return me the results but when I do '#search = #search2 + #search1', I get the error message below:
TypeError in ApparatusesController#app_used_by_Lab
can't convert Searchlogic::Search into Array
Is it not possible to use searchlogic on arrays?
Is there any solution to the above problem?
Thanks a lot for your precious help.
Please Try this:
#search = #search2.to_s + #search1.to_s
try this:
#search = #search2.concat(#search1)