I am creating a simle application with ruby and mongo mapper and I want to test it with rspec, the setup is like this:
class Entry
include MongoMapper::Document
key :things, Array
key :date_created, Date
end
And the service (thinking in changing it to helper) looks like this:
class EntryService
def save_entry (date, items)
entry = Entry.new(:date_created => date, :things => items )
entry.save!
return 'success'
end
end
My question is, how do I test the save_entry method of the EntryService class without hitting the Database?
Related
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
I prepared view in my PostgresDB called user_details. I created UserDetail entity and UserDetailRepository. Here you have shortened version of my view to visualize my problem:
CREATE VIEW user_details AS
SELECT id, user_name FROM users WHERE user_name like '$1#%'
My question is how to inject parameter using Hanami repository?
I can use raw sql in my repos which is described here http://hanamirb.org/guides/models/repositories/ but I prefer to create view in postgres using migrations. I don't want to improve query but to know if I can user parameterized queries with Hanami. Thanks for all answers
PostgreSQL doesn't support parameterized views in the way you described. It can have views that call a function which in order can access the current session state and you can set that state just before selecting data from the view. However, I'd recommend you define a method with an argument instead
class UserRepo
def user_details(prefix)
root.project { [id, user_name] }.where { user_name.ilike("#{ prefix }%") }.to_a
end
end
What you get with this is basically the same. If you want to use user_details as a base relation you can define a private method on the repo and call it from other public methods
class UserRepo
def user_details_filtered(user_name, min_user_id = 0)
user_details(prefix).where { id > min_user_id }.to_a
end
def user_details_created_after(user_name, after)
user_details(prefix).where { created_at > after }.to_a
end
private
# Don't call this method from the app code, this way
# you don't leak SQL-specific code into your domain
def user_details(prefix)
root.project { [id, user_name] }.where { user_name.ilike("#{ prefix }%") }
end
end
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
I am trying to store my ruby object in couchdb with couchrest. I am extending my model from CouchRest::Model::Base But still i am unable to see the changes in db.
I've defined Server as CouchRest.new also mentioned in model to use_database 'players'
# Controller Method
get '/new/:name' do
DB = SERVER.database!('players')
#new_player = Player.new(params['name'])
#new_player.create
"success: #{#new_player.persisted?}" #shows true
# Model
class Player < CouchRest::Model::Base
use_database 'players'
property :name ,String
timestamps!
def initialize(arg)
#name=arg
end
end
How To Persist the object?
How can i retreive all persisted objects?
Is there any simple applications which i can refer to?
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.