I want to display an dynamically chosen image, thus within the html I call upon the variable #background_img, which contains the url to a specific picture. However, doing
<body style='background-image: url(<%=#background_img%>);'>
simply refuses to display the image for the background. Am I misinterpreting how ERB works, because wouldn't Rails simply precompile the CSS and end up with a working HTML image fetch? Using the Chrome Developer Tools when previewing my app reveals url(), and obviously an empty parameter can't fetch the image.
EDIT:
Just wanted to add that I would rather not have to download the images, but keep the urls I already have prepared.
This is the WeatherMan class:
require 'rest-client'
class WeatherMan
#images within accessible data structures, designed to be expandable
def initialize
#hot = ['https://farm2.staticflickr.com/1515/23959664094_9c59962bb0_b.jpg']
#rain = ['https://farm8.staticflickr.com/7062/6845995798_37c20b1b55_h.jpg']
end
def getWeather(cityID)
response = JSON.parse RestClient.get "http://api.openweathermap.org/data/2.5/weather?id=#{cityID}&APPID=bd43836512d5650838d83c93c4412774&units=Imperial"
return {
temp: response['main']['temp'].to_f.round,
cloudiness: response['clouds']['all'].to_f.round,
humidity: response['main']['humidity'].to_f.round,
windiness: response['wind']['speed'],
condition_id: response['weather'][0]['id'].to_f,
condition_name: response['weather'][0]['main'],
condition_description: response['weather'][0]['description'],
condition_img: response['weather'][0]['icon']
}
end
def getImg(temp)
if temp <= 100 #CHANGE!!!
return #rain[rand(#rain.length)]
elsif temp <= 32
return nil
elsif temp <= 50
return nil
elsif temp <= 75
return nil
elsif temp <= 105
return nil
end
end
end
So sorry about the formatting, on mobile right now.
Now, the controller class:
load File.expand_path("../../data_reader.rb", __FILE__)
load File.expand_path("../../weatherstation.rb", __FILE__)
class PagesController < ApplicationController
def home
# `sudo python /home/pi/Documents/coding/raspberryPI/weatherStation/app/led_blink.py`
server = WeatherMan.new
#outside_data = server.getWeather(4219934)
#sensor_temp = DRead.read_data(File.expand_path('../../data.txt', __FILE__), 'temperature')
#sensor_temp = (#sensor_temp.to_f * (9.0/5) + 32).round(2)
#background_img = server.getImg(#outside_data[:temp])
end
end
The problem seems to be that #background_img is not populated.
The reason for this seems to be your Weatherman class. I will attempt to rectify the issue...
Controller
If you're calling #background_img on your body tag, it means it's accessible at every controller action. Thus, instead of declaring it in a solitary home action, you need to make it available each time you load your views:
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
before_action :set_background
private
def set_background
server = WeatherMan.new
#outside_data = server.getWeather(4219934)
#sensor_temp = DRead.read_data(File.expand_path('../../data.txt', __FILE__), 'temperature')
#sensor_temp = (#sensor_temp.to_f * (9.0/5) + 32).round(2)
#background_img = server.getImg(#outside_data[:temp])
end
end
--
Class
The main issue I see is that your class is not giving you a value. I'll attempt to refactor your class, although I can't promise anything:
require 'rest-client'
class WeatherMan
##static = {
hot: 'https://farm2.staticflickr.com/1515/23959664094_9c59962bb0_b.jpg',
rain: 'https://farm8.staticflickr.com/7062/6845995798_37c20b1b55_h.jpg'
}
def getWeather(cityID)
response = JSON.parse RestClient.get weather_url(cityID)
return {
temp: response['main']['temp'].to_f.round,
cloudiness: response['clouds']['all'].to_f.round,
humidity: response['main']['humidity'].to_f.round,
windiness: response['wind']['speed'],
condition_id: response['weather'][0]['id'].to_f,
condition_name: response['weather'][0]['main'],
condition_description: response['weather'][0]['description'],
condition_img: response['weather'][0]['icon']
}
end
def getImg(temp)
#### This should return the image ####
#### Below is a test ####
##static[:hot]
end
private
def weather_url city
"http://api.openweathermap.org/data/2.5/weather?id=#{city}&APPID=bd43836512d5650838d83c93c4412774&units=Imperial"
end
end
--
View
You need to make sure you're getting returned data from your controller in order to populate it in your view.
Because your getImg method is returning nil, you're getting a nil response. I have amended this for now with one of the flickr links you have included in the class.
If you always have a returned image, the following should work:
#app/views/layouts/application.html.erb
<body style='background-image: url(<%= #background_img %>);'>
Because your #background_img is an external URL, the above should work. If you were using a file from your asset_pipeline, you'd want to use image_url etc
Related
I've become confused while writing custom to_json and from_json methods for a class. I have actually found a solution, but don't understand why it works, nor why my initial attempt does not work.
I have a People class that initializes by taking an instance of a Person class as a paramater.
The to_json/from_json methods in Person have been copied in from a generic
external module, and therefore a bit wordy...but worked when I tested it on an individual instance of a Person object.
The problem comes when re-creating the People object from JSON. For the #person instance variable, I'm expecting:
#<Person:0x00000001a0b440 #name="Jon", #age=22, #gender="male">
Instead, I'm getting #person as an array (and thus, only the keys):
#<People:0x00000001b5c038 #person=["#name", "#age", "#gender"]>
Full code is as follows:
require "json"
class Person
attr_accessor :name, :age, :gender
def initialize(name, age, gender)
#name = name
#age = age
#gender = gender
end
def to_json
obj = {}
instance_variables.map do |var|
obj[var] = instance_variable_get(var)
end
JSON.dump(obj)
end
def from_json(string)
obj = JSON.parse(string)
obj.keys.each do |key|
instance_variable_set(key, obj[key])
end
end
end
class People
attr_accessor :person
def initialize(person)
#person = person
end
def to_json
obj = {}
obj[:person] = #person.to_json
JSON.dump(obj)
end
def from_json(string)
obj = JSON.parse(string, {:symbolize_names => true})
person = Person.new("", 0, "")
#person = person.from_json(obj[:person])
end
def <<(person)
#persons << person
end
end
After re-writing the to_json and from_json methods as below, the problem seems to have been solved...and now correctly re-assembles #person as expected.
def to_json
obj = {}
obj[:persons] = [#person.to_json]
JSON.dump(obj)
end
def from_json(string)
obj = JSON.parse(string, {:symbolize_names => true})
persons = []
obj[:persons].each do |person_string|
person = Person.new("", 0, "")
person.from_json(person_string)
persons << person
end
#person = persons[0]
end
I'm happy to have found a solution, but I can't understand why encasing the single Person object in an array would solve the situation.
I'm sure there are many other ways to solve this particular situation (and other methods completely... eg: other gems, or using Rails Active Support...), but I'm simply trying to get a more solid understanding why my initial idea doesn't work...to help later on when things get more complicated.
Thank you for any help you can offer...
Your first solution works. You simply forgot to return from your method. See below:
def from_json(string)
obj = JSON.parse(string, {:symbolize_names => true})
person = Person.new("", 0, "")
#person = person.from_json(obj[:person])
obj #RETURN THE OBJECT HERE
end
In the second solution you are still missing the return value however Ruby implicitly returns the last evaluated expression from the method which by chance happens to be correct. This is the same reason why your first solution didn't work.
I have a very simple model that I wish to serialize in a Rails (5) API. I want to produce the resulting JSON keys as CamelCase (because that's what my client expects). Because I expect the model to increase in complexity in future, I figured I should use ActiveModelSerializers. Because the consumer of the API expects a trivial JSON object, I want to use the :attributes adapter. But, I cannot seem to get AMS to respect my setting of :key_transform, regardless of whether I set ActiveModelSerializers.config.key_transform = :camel in my configuration file or create the resource via s = ActiveModelSerializers::SerializableResource.new(t, {key_transform: :camel}) (where t represents the ActiveModel object to be serialized) in the controller. In either case, I call render json: s.as_json.
Is this a configuration problem? Am I incorrectly expecting the default :attributes adapter to respect the setting of :key_transform (this seems unlikely, based on my reading of the code in the class, but I'm often wrong)? Cruft in my code? Something else?
If additional information would be helpful, please ask, and I'll edit my question.
Controller(s):
class ApplicationController < ActionController::API
before_action :force_json
private
def force_json
request.format = :json
end
end
require 'active_support'
require 'active_support/core_ext/hash/keys'
class AvailableTrucksController < ApplicationController
def show
t = AvailableTruck.find_by(truck_reference_id: params[:id])
s = ActiveModelSerializers::SerializableResource.new(t, {key_transform: :camel})
render json: s.as_json
end
end
config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module AvailableTrucks
class Application < Rails::Application
config.api_only = true
ActiveModelSerializers.config.key_transform = :camel
# ActiveModelSerializers.config.adapter = :json_api
# ActiveModelSerializers.config.jsonapi_include_toplevel_object = false
end
end
class AvailableTruckSerializer < ActiveModel::Serializer
attributes :truck_reference_id, :dot_number, :trailer_type, :trailer_length, :destination_states,
:empty_date_time, :notes, :destination_anywhere, :destination_zones
end
FWIW, I ended up taking an end-around to an answer. From previous attempts to resolve this problem, I knew that I could get the correct answer if I had a single instance of my model to return. What the work with ActiveModel::Serialization was intended to resolve was how to achieve that result with both the #index and #get methods of the controller.
Since I had this previous result, I instead extended it to solve my problem. Previously, I knew that the correct response would be generated if I did:
def show
t = AvailableTruck.find_by(truck_reference_id: params[:id])
render json: t.as_json.deep_transform_keys(&:camelize) unless t.nil?
end
What had frustrated me was that the naive extension of that to the array returned by AvailableTruck.all was failing in that the keys were left with snake_case.
It turned out that the "correct" (if unsatisfying) answer was:
def index
trucks = []
AvailableTruck.all.inject(trucks) do |a,t|
a << t.as_json.deep_transform_keys(&:camelize)
end
render json: trucks
end
So I'm trying to write a method in the model that will allow me to return posts who have a specific field value that is greater than 0.
So I have posts that have fields that are essentially tags. Basically I post has four fields, hiphop, electro, house and pop. Each field has a value between 0 and 10.
I'm trying to make it so if someone clicks on a button the the view that says "Hip Hop" it will return all posts that have a hiphop field value that is greater than 0.
I know this is wrong but I'm thinking something like this
def self.tagSearch(query)
where("#{query} > 0")
end
and in my controller I would have something like this
def index
if params[:search]
#songs = Song.search(params[:search]).order("created_at DESC")
elsif params[:tag]
#songs = Songs.tagSearch(params[:tag]).order("created_at DESC")
else
#songs = Song.all
end
end
And I'm not sure about the view but maybe a button that passes the tag value parameter. The thing is I just want it to be a button, I don't need them to input anything.
I hope this isn't too confusing.
Thank you!
Matt
To expand on RaVen post:
1) Use ruby naming conventions tagSearch should be tag_search; methods are snake case (lower case with underscores).
2) where("#{query} > 0") is exposing you to SQL injection attacks - recommended to install the brakeman gem which can expose security issues like this:
http://brakemanscanner.org/docs/warning_types/sql_injection/
http://brakemanscanner.org/docs/
3) You can simplify your code by chaining scopes, scopes that return nil will not effect the query
class Song
scope :search, -> (query) do
where("name LIKE ?", "#{query}%") if query.present?
end
scope :tag_search, -> (tag) do
where(tag > 0) if tag.present?
end
scope :ordered, -> do
order(created_at: :desc)
end
end
class SongsController
def index
#songs = Song.search(params[:search])
.tag_search(params[:tag])
.ordered
end
end
4) Making queries based on a user specified column and avoiding sql injection:
This is one way to do it, there are probably other better ones available, like using the models arel_table, anyhow this one is pretty straight forward
scope :tag_search, -> (tag) do
where("#{self.white_list(tag)} > 0") if tag.present?
end
def self.white_list(column_name)
# if the specified column_name matches a model attribute then return that attribute
# otherwise return nil which will cause a sql error
# but it won't let arbitrary sql execution
self.attribute_names.detect { |attribute| attribute == column_name }
end
Rails support "scopes" which return an ActiveRecord::Relation which means you can chain them together.
class Song
scope :tag_search, -> (something) { where(something > 0) }
scope :ordered, -> { order(created_at: :desc) }
end
class SongsController
def index
if params[:search]
#songs = Song.search(params[:search]).ordered
elsif params[:tag]
#songs = Songs.tag_search(params[:tag]).ordered
else
#songs = Song.all
end
end
end
I would overthink the design of this.
Plus your tagSearch function is really dangerous. SQL INJECTION!
I am coding a custom Liquid tag as Jekyll plugin for which I need to preserve some values until the next invocation of the tag within the current run of the jekyll build command.
Is there some global location/namespace that I could use to store and retrieve values (preferably key-value pairs / a hash)?
You could add a module with class variables for storing the persistent values, then include the module in your tag class. You would need the proper accessors depending on the type of the variables and the assignments you might want to make. Here's a trivial example implementing a simple counter that keeps track of the number of times the tag was called in DataToKeep::my_val:
module DataToKeep
##my_val = 0
def my_val
##my_val
end
def my_val= val
##my_val = val
end
end
module Jekyll
class TagWithKeptData < Liquid::Tag
include DataToKeep
def render(context)
self.my_val = self.my_val + 1
return "<p>Times called: #{self.my_val}</p>"
end
end
end
Liquid::Template.register_tag('counter', Jekyll::TagWithKeptData)
I have a json file. I am using it to store information, and as such it is constantly going to be both read and written.
I am completely new to ruby and oop in general, so I am sure I am going about this in a crazy way.
class Load
def initialize(save_name)
puts "loading " + save_name
#data = JSON.parse(IO.read( $user_library + save_name ))
#subject = #data["subject"]
#id = #data["id"]
#save_name = #data["save_name"]
#listA = #data["listA"] # is an array containing dictionaries
#listB = #data["listB"] # is an array containing dictionaries
end
attr_reader :data, :subject, :id, :save_name, :listA, :listB
end
example = Load.new("test.json")
puts example.id
=> 937489327389749
So I can now easily read the json file, but how could I write back to the file - refering to example? say I wanted to change the id example.id.change(7129371289)... or add dictionaries to lists A and B... Is this possible?
The simplest way to go to/from JSON is to just use the JSON library to transform your data as appropriate:
json = my_object.to_json — method on the specific object to create a JSON string.
json = JSON.generate(my_object) — create JSON string from object.
JSON.dump(my_object, someIO) — create a JSON string and write to a file.
my_object = JSON.parse(json) — create a Ruby object from a JSON string.
my_object = JSON.load(someIO) — create a Ruby object from a file.
Taken from this answer to another of your questions.
However, you could wrap this in a class if you wanted:
class JSONHash
require 'json'
def self.from(file)
self.new.load(file)
end
def initialize(h={})
#h=h
end
# Save this to disk, optionally specifying a new location
def save(file=nil)
#file = file if file
File.open(#file,'w'){ |f| JSON.dump(#h, f) }
self
end
# Discard all changes to the hash and replace with the information on disk
def reload(file=nil)
#file = file if file
#h = JSON.parse(IO.read(#file))
self
end
# Let our internal hash handle most methods, returning what it likes
def method_missing(*a,&b)
#h.send(*a,&b)
end
# But these methods normally return a Hash, so we re-wrap them in our class
%w[ invert merge select ].each do |m|
class_eval <<-ENDMETHOD
def #{m}(*a,&b)
self.class.new #h.send(#{m.inspect},*a,&b)
end
ENDMETHOD
end
def to_json
#h.to_json
end
end
The above behaves just like a hash, but you can use foo = JSONHash.from("foo.json") to load from disk, modify that hash as you would normally, and then just foo.save when you want to save out to disk.
Or, if you don't have a file on disk to begin with:
foo = JSONHash.new a:42, b:17, c:"whatever initial values you want"
foo.save 'foo.json'
# keep modifying foo
foo[:bar] = 52
f.save # saves to the last saved location