I've got a method sitting in a Services class. This method is going to take the name of a service and a key:value pair of an attribute I want to build a string query for to call out to the service i'm passing in.
I'm sending this build string query to the service via RestClient and capturing the response in a variable: #response
I want to carry this variable out of the Services class and use it. I've got attr_reader included in my class but i keep getting nil for #response when I try to access the response outside of Services.
What am I missing?
Example of my code:
class Services
attr_reader :response
def query_method(service,key,value)
where = "#{key}=#{value}"
#url = root_url + service + where
#response = RestClient::Request.execute(:method => :get, :url => #url)
end
end
Related
There is a custom function that returns a class instance.
Puppet::Functions.create_function(:'my_custom_function') do
dispatch :make do
end
class Sample
attr_reader :value
def initialize( value )
#value = value
end
def to_s()
'<Sample %d>' % [ value ]
end
end
def make()
Sample.new(1)
end
end
ie:
class myclass {
$data = my_custom_function()
}
Is it possible to use the $data as a complex type in an ERB template?
Due to the "to_s" defined for the class this works:
<%= #data %>
yields
<Sample 1>
but it doesn't appear possible to access any of the instance methods (ie: #data.value)
When trying to access .value, the following error is typical:
Detail: undefined method `value' for #<Puppet::Pops::Loader::RubyFunctionInstantiator::Sample:0x7ace1824>
Is accessing class methods at all possible? If so, how?
Thanks.
I am working on a backend of an application written in Sinatra.
It has a route "/notifications"
which renders all the notifications in JSON.
I want to change the json structure and wrote some custom serializer and it is failing now.
the error i get is
"{"message":"undefined method `read_attribute_for_serialization' for nil:NilClass"}"
I have a file called webservice/notification.rb
which selects a notification serializer.
the code is something like this
serializer = NotificationSerializer
json serialize(notifications, root: :notifications, each_serializer: serializer)
The NotificationSerializer is something like this.
class NotificationSerializer < Serializer
attributes :id, :tag, :event, :time, :read
has_one :reference, polymorphic: true, include: true
The reference here can be a lot of things.
the notification model defines reference as
def reference
company || contact || deal || invitation || meeting || todo || reference_email || reference_user ||
contact_import_job
end
now all of these models in reference have there Serializer implements in directory Serializer/*
I want to make custom Serializers for all of these which will render limited information.
how can I call my custom Serializer for things inside reference.
I wrote a custom serializer for notifications and called it like this inside my refernce function and it worked.
...|| UserNotificationSerializer.new(reference_user) || ...
but if i do the same for my other models i get the error given above.
what would be the correct way to call my custom serializers.
A good way to do it is to write an instance method on the model:
class Notification < ActiveRecord::Base
def public_attributes # or call it whatever
attributes_hash = attributes
# in activerecord, the attributes method turns a model instance into a hash
# do some modifications to the hash here
return attributes_hash
end
end
then say you're returning json in a controller:
get '/some_route' do
#notifications = Notification.all # or whatever
serialized_notifications = #notifications.map(&:public_attributes)
# For a single record, you could do #notification.public_attributes
json_data = serialized_notifications.to_json # a serialized array of hashes
content_type :json
return json_data
end
class Oauth
RESPONSE_TYPE = 'response_type'
CLIENT_ID = 'client_id'
REDIRECT_URI = 'redirect_uri'
AUTHORIZATION_TOKEN = 'authorization_token'
REQUIRED_PARAMS = [RESPONSE_TYPE, CLIENT_ID, REDIRECT_URI]
VALID_PARAMS = REQUIRED_PARAMS
attr_reader :errors
def initialize(params)
#params = params
#errors = []
end
def valid?
REQUIRED_PARAMS.all?{ |param| valid_params.has_key?(param) }
end
# private
def valid_params
#params.slice(*VALID_PARAMS)
end
end
I would like to collect missing #{param} key errors after calling valid? method.
You can try to make your OAuth Object an ActiveModel it behaves like an ActiveRecord Model but is not backed via DB. ActiveModel allows you to use validations as you would in an AR model, so fetching the validation errors would be likewise.
I have a small blogging app running in Rails 4.1. It lets a user log in and then create, edit, and delete basic posts with a title and body. It all runs though the user interface perfectly.
I'm trying to write a custom rake task (that will later be attached to a chron job) to automatically create posts. Right now I have this:
namespace :blog do
desc "Automatically post to all users accounts"
task auto_post: :environment do
post_title = "Automated Blog Post Title"
post_body = "Hello World!"
Post.create!({:title => post_title,
:body => post_body})
end
end
As best I know it's properly namespaced, etc. and can be run using rake blog:auto_post. The controller for Post looks like this:
class PostsController < ApplicationController
def index
#posts = current_user.posts
end
def new
#post = Post.new
end
def create
#post = Post.new post_params
if #post.save
current_user.posts << #post
flash[:notice] = "New post created!"
redirect_to posts_path
else
render 'new'
end
end
def edit
#post = Post.find params[:id]
end
.....
private
def post_params
params.require(:post).permit(:title, :body)
end
end
As I understand it, I should be able to pass my :title and :body to the Post.new action and have it work. I suspect that I'm not interacting with strong parameters properly. Can anyone help clear this up for me.
EDIT: My psql shows the posts hitting the database so I'm close. Not sure why they're not appearing in the app interface though.
Post.new creates a new object but does not persist it to the database. You need to use Post.create!({:title => post_title, :body => post_body}) instead.
Rake tasks do not call the controller and strong parameters don't come into the picture in a rake task which is run locally. They are there to protect your app from the big, bad Internets.
I am new to Ruby and came from C# world. In C# it is legal to do stuff like this:
public class Test
{
public void Method()
{
PrivateMethod();
}
private void PrivateMethod()
{
PrivateStaticMethod();
}
private static void PrivateStaticMethod()
{
}
}
Is it possible to do something similar in Ruby?
A little bit of context: I have a Rails app... One of the models has a private method that sets up some dependencies. There is a class method that creates initialized instance of the model. For legacy reasons there are some instances of the model that are not initialized correctly. I added an instance method that initializes 'uninitialized' instances where I want to do same initialization logic. Is there a way to avoid duplication?
Sample:
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
model.init_some_dependencies # this fails
model
end
def initialize_instance
// do some other work
other_init
// call private method
init_some_dependencies
end
private
def init_some_dependencies
end
end
I tried to convert my private method to a private class method, but I still get an error:
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
MyModel.init_some_dependencies_class(model)
model
end
def initialize_instance
# do some other work
other_init
# call private method
init_some_dependencies
end
private
def init_some_dependencies
MyModel.init_some_dependencies_class(self) # now this fails with exception
end
def self.init_some_dependencies_class(model)
# do something with model
end
private_class_method :init_some_dependencies_class
end
First let me try to explain why the code does not work
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
# in here, you are not inside of the instance scope, you are outside of the object
# so calling model.somemething can only access public method of the object.
model.init_some_dependencies
...
end
...
You could bypass private calling of the method with model.send :init_some_dependencies. But I think in this case there is probably better solution.
I would guess that init_some_dependencies probably contain more business / domain logic rather than persistence. That's why I would suggest to pull out this logic into a "Domain Object" (or some call it Service Object). Which is just a plain ruby object that contain domain logic.
This way you could separate persistence logic to ActiveRecord and the domain logic to that class. Hence you will not bloat the ActiveRecord Model. And you get the bonus of testing
the domain logic without the need of ActiveRecord. This will make your test faster.
You could create a file say `lib/MyModelDomain.rb'
class MyModelDomain
attr_accessor :my_model
def initialize(my_model)
#my_model = my_model
end
def init_some_dependencies
my_model.property = 'some value example'
end
end
Now you could use this object say something like this
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
domain = MyModelDomain.new(model)
domain.init_some_dependencies
domain.my_model
end
def initialize_instance
# do some other work
other_init
domain = MyModelDomain.new(self)
domain.init_some_dependencies
end
end
You might also want to move the initialize_instance if you think it's necessary
Some resource that go deep into this pattern:
http://railscasts.com/episodes/398-service-objects
https://www.destroyallsoftware.com/screencasts/catalog/extracting-domain-objects
You can use
model = MyModel.new
model.send :init_some_dependencies
to bypass method visibility checks.
In C# it is legal to do stuff like this:
public class Test
{
public void Method()
{
PrivateMethod();
}
private void PrivateMethod()
{
PrivateStaticMethod();
}
private static void PrivateStaticMethod()
{
}
}
Is it possible to do something similar in Ruby?
Yes:
class Test
def method
private_method()
end
def self.greet
puts 'Hi'
end
private_class_method :greet
private
def private_method
self.class.class_eval do
greet
end
end
end
Test.new.method
Test.greet
--output:--
Hi
1.rb:23:in `<main>': private method `greet' called for Test:Class (NoMethodError)
But ruby doesn't strictly enforce privacy. For instance,
class Dog
def initialize
#private = "secret password"
end
end
puts Dog.new.instance_variable_get(:#private)
--output:--
secret password
ruby gives you the freedom to access private things with a little bit of extra effort:
Test.new.method
Test.class_eval do
greet
end
--output:--
Hi
Hi
In ruby, a private method only means that you cannot explicitly specify a receiver for the method, i.e. there can't be a name and a dot to the left of the method. But in ruby, a method without a receiver implicitly uses self as the receiver. So to call a private method, you just have to create a context where self is the correct receiver. Both class_eval and instance_eval change self inside the block to their receiver, e.g.
some_obj.instance_eval do
#Inside here, self=some_obj
#Go crazy and call private methods defined in some_obj's class here
end
You can apply those rules to this situation:
(ahmy wrote:)
First let me try to explain why the code does not work
class MyModel < ActiveRecord::Base
def self.create_instance
model = MyModel.new
# in here, you are not inside of the instance scope, you are outside of the object
# so calling model.somemething can only access public method of the object.
model.init_some_dependencies # this fails
... end ...
"Context this" and "scope that"--what a headache. All you have to remember is: you cannot call a private method with an explicit receiver. The method init_some_dependencies was defined as a private method--yet it has "model." written to the left of it. That is an explicit receiver. Bang! An error.
Here is a solution:
class MyModel
def self.create_instance
#In here, self=MyModel
puts self
model = MyModel.new
model.instance_eval do #Changes self to model inside the block
#In here, self=model
init_some_dependencies #Implicitly uses self as the receiver, so that line is equivalent to model.init_some_dependencies
end
end
private
def init_some_dependencies
puts "Dependencies have been initialized!"
end
end
MyModel.create_instance
--output:--
MyModel
Dependencies have been initialized!
Or as ahmy and LBg pointed out, you can use Object#send() to call private methods:
class MyModel
def self.create_instance
model = MyModel.new
model.send(:init_some_dependencies, 10, 20)
end
private
def init_some_dependencies(*args)
puts "Dependencies have been initialized with: #{args}!"
end
end
MyModel.create_instance
--output:--
Dependencies have been initialized with: [10, 20]!
acturally, it surely does.
Ruby's some OO strategies(private & public keywords etc.) comes from C++, so you can get almost same usage.