ruby - Rails JSON data from other domain? -
ruby - Rails JSON data from other domain? -
i trying json info other domain. used code:
class empinfocontroller < applicationcontroller require 'httparty' def empdata uri = httparty.get("http://www.somesite.com/jsondata/xyz") resp = json.parse(uri.body) @empdata = resp end end i able json info parsed resp when force @empdata , seek utilize using javascript not seem find right keys/hashes.
is there way dissect json hash , output view?
json info - resp { "empid123456": { "first_name": "john", "last_name": "doe", "title": "mr", "age": "32", "blood_group": "b+" } } can moving @empdata , utilize @empdata[:first_name] retreive later in view?
i new rails , need guidance on every step of project.
wrap json info in ruby class , set in "models" directory app/models/json_data.rb:
class jsondata attr_reader :emp def initialize(attributes) @emp = attributes[:emp] end def self.from_json(json_string) parsed = json.parse(json_string) emp = emp.new(parsed['empid123456']) new(:emp => emp) end end create active model class emp , place in app/models/emp.rb:
class emp include activemodel::serializers::json include activemodel::validations attributes = [:first_name, :last_name, :title, :age, :blood_group] attr_accessor *attributes ###add activemodel validations here ### def initialize(attributes = {}) self.attributes = attributes end def attributes attributes.inject( activesupport::hashwithindifferentaccess.new ) |result, key| result[key] = read_attribute_for_validation(key) result end end def attributes= (attrs) attrs.each_pair {|k, v| send("#{k}=", v)} end def read_attribute_for_validation(key) send(key) end end in controller can this:
def empdata uri = httparty.get("http://www.somesite.com/jsondata/xyz") @empdata = jsondata.from_json(uri.body) end in view can use:
@empdata.first_name @empdata.last_name to retrieve respective values.
ruby-on-rails ruby json
Comments
Post a Comment