observers for mongoid with rails-observers rails4 - ruby-on-rails

I am interested in any solution the title describes.
My gemfile is:
gem "rails", "~> 4.0.0"
gem "mongoid", "~> 3.1.3"
gem 'rails-observers'
I want to use observers on my mongoid models but I receive this error:
https://github.com/mongoid/mongoid/issues/3108
Any ideas are welcome

I just implemented this gem, https://github.com/chamnap/mongoid-observers/, because I often need it. Please have a look and give me feedback.

It looks like you need to include the module in each model and set the observers.
class ORM
include ActiveModel::Observing
end
# Calls PersonObserver.instance
ORM.observers = :person_observer
# Calls Cacher.instance and GarbageCollector.instance
ORM.observers = :cacher, :garbage_collector
# Same as above, just using explicit class references
ORM.observers = Cacher, GarbageCollector
https://github.com/rails/rails-observers/blob/master/lib/rails/observers/active_model/observing.rb#L19

Related

Rails 5 - How to create custom scaffold generator?

The goal is for command...
bin/rails generate custom_scaffold Thing
... to generate the following 6 files:
db/migrate/201812031331_create_things.rb
app/models/thing.rb
app/controllers/things_controller.rb
app/serializers/thing_serializer.rb
test/fixtures/things.yml
test/integration/requests/things_request_test.rb
... using Rails 5.
My current setup does generate app/models/thing.rb but does not populate it with Thing.
Expected:
class Thing < ApplicationRecord
end
Currently:
class <%= class_name %> < ApplicationRecord
end
I have read through these Rails guides but to little avail.
Does anyone have a working example?
My setup:
# lib/generators/custom_scaffold/custom_scaffold_generator.rb
class CustomScaffoldGenerator < Rails::Generators::NamedBase
source_root File.expand_path('templates', __dir__)
def create_files
copy_file 'migration.rb', "db/migrate/#{timestamp}_create_#{plural_name}.rb"
copy_file 'model.rb', "app/models/#{file_name}.rb"
copy_file 'controller.rb', "app/controllers/#{plural_name}_controller.rb"
copy_file 'serializer.rb', "app/serializers/#{file_name}_serializer.rb"
copy_file 'fixture.yml', "test/fixtures/#{plural_name}.yml"
copy_file 'request_test.rb', "test/integration/requests/#{plural_name}_request_test.rb"
end
private
def timestamp
Time.now.utc.strftime('%Y%m%d%H%M%S')
end
end
# lib/generators/custom_scaffold/templates/model.rb
class <%= class_name %> < ApplicationRecord
end
# lib/generators/custom_scaffold/templates/controller.rb
module V1
module Public
class <%= class_name.pluralize %>Controller < ApplicationController
end
end
end
# lib/generators/custom_scaffold/templates/migration.rb
# Ignore for now
# lib/generators/custom_scaffold/templates/serializer.rb
# Ignore for now
# lib/generators/custom_scaffold/templates/fixture.yml
# Ignore for now
# lib/generators/custom_scaffold/templates/request_test.rb
# Ignore for now
# Gemfile
source 'https://rubygems.org'
ruby '2.4.1'
gem 'rails', '~> 5.1.6'
gem 'puma', '~> 3.7'
gem 'pg'
gem 'rack-cors', require: 'rack/cors'
gem 'olive_branch'
gem 'fast_jsonapi'
gem 'awesome_print'
gem 'byebug', '~> 10.0', groups: %i[development test]
gem 'yaml_db'
group :development do
gem 'listen', '>= 3.0.5', '< 3.2'
gem 'mina', '~> 1.2', require: false
gem 'mina-puma', require: false
gem 'rubocop', require: false
gem 'annotate', require: false
end
You need to specify the file as a Thor template. Rails uses Thor templates for generating templates with ERB style code inside them.
Replace:
copy_file 'model.rb', "app/models/#{file_name}.rb"
With:
template 'model.rb.tt', "app/models/#{file_name}.rb"
By adding the .tt extension you're telling the generator to handle the file as a Thor template, which will interpret the Ruby code (ERB style) inside the file and then create a file with that same name minus the .tt extension. Any file you have without the .tt extension the generator will copy wholesale, without executing any of the code inside.
A useful tip: Sometimes you want to leave some ERB code inside a Thor template file without it being executed. By default any ERB style tags inside a .tt file will be process and in it's place a string will be written to the output file. You can avoid the processing of ERB tags but using a double percent sign in the tag.
For example, lets say you have a file named foo.erb.tt, which will create the file foo.erb when your generator runs. Let's also say we have a article_name variable and it's value is Breaking News
If you put <%= article_name %> in the file it will write Breaking News to the foo.erb.
If you put <%%= article_name %> (notice the %%) it will write <%= article_name %>to the foo.erb.
I found the following reference handy when learning this stuff.
Rails Application Templates article at Rails Guides.
Creating and Customizing Rails Generators & Templates article at Rails Guides.
Thor Actions Docs these are the commands used in our template.rb file.
Thor comes with several actions that help with script and generator tasks. You might be familiar with them since some came from Rails Templates. They are: say, ask, yes?, no?, add_file, remove_file, copy_file, template, directory, inside, run, inject_into_file and a couple more.

Rails 5 install error (DEPRECATION WARNING: alias_method_chain is deprecated)

I'm running into this error after installing rails 5.0.0 on my project. I'm starting to think it's Devise gem or something. I tried multiple ways, but can't seem to figure it out.
I've tried this for devise gem, but same result.
gem 'devise', :github => 'plataformatec/devise', :branch => 'master'
DEPRECATION WARNING: alias_method_chain is deprecated. Please, use Module#prepend instead. From module, you can access the original method using super. (called from <top (required)> at /home/nitrous/code/uvesty/config/environment.rb:5)
Exiting
/home/nitrous/code/uvesty/.bundle/gems/actionpack-5.0.0/lib/action_dispatch/middleware/stack.rb:108:in `assert_index': No such middleware to insert after: ActionDispatch::ParamsParser (RuntimeError
I also thought I might need to change all my
#user = User.find(params[:id])
to
#user = User.find_by(id: params[:id])
First change devise declaration in Gemfile like
gem "devise", '~> 4.0.0.rc1'
Secondly, you don't need to change this line, as find method is NOT deprecated.
#user = User.find(params[:id])
Please check what new in rails 5
The issue was the gem rails_admin. I removed it and it's all fine now. It seems they might have not updated their gem for rails 5.0.

Getting uninitialized constant error from unused gem

I was trying to use the Addressable gem in a specific action in Rails.
My usual practice is to include the gem in the Gemfile, and then require the module where needed.
Gemfile:
gem 'addressable'
some_controller.rb:
class SomeController < ApplicationController
def new
require "addressable/uri"
current_url = Addressable::URI.parse(request.original_url)
....
end
end
However, I was getting a 500 error on other actions/controllers that did not use the gem.
Error during failsafe response: uninitialized constant Addressable
Finally, I removed all the code calling addressable, but kept the entry in the gemfile, and the 500 error persists on all actions. Why would this be?
Not sure why you're getting that specific error, but with a gem like Addressable where you don't want an automatic require 'addressable' performed then in your Gemfile you should have:
gem 'addressable', :require => false

Rails 3: Routing Error - uninitialized constant MyController::Google

I'm using the google-api-client gem (gem google-api-client, '0.4.1' in my Gemfile). The following code caused the error uninitialized constant MyController::Google:
class MyController < ApplicationController
def index
#client = Google::APIClient.new
end
end
Specifying ::Google::APIClient didn't help, the error then said uninitialized constant Google.
Simply adding a require 'google/api_client' at the top of the file made this go away, so it seems there's something wrong in how auto-loading is being done. Not sure what's going on here exactly, specifying the gem in my Gemfile should have automatically required the gem, right? I have restarted the rails server btw.
Try adding a :require => 'google/api_client' where you specify the google api client gem in the Gemfile
gem 'google-api-client', :require => 'google/api_client'
This tells bundler that the correct way to require the gem 'google-api-client' is to require 'google/api_client'

undefined method `will_paginate', Rails 3.1 / DataMapper

Newly installed will_paginate 3.0.0
gem 'will_paginate', '~> 3.0.0', :require=>'will_paginate/data_mapper'
Running a controller query:
#tickets = Ticket.paginate(:page => params[:page], :per_page => 5,:username => #ticket.username)
Which works, pulls up all the tickets for a user and paginates in 5's if I put ?page=X where x is a page number in the url.
=will_paginate(#tickets)
in the view does not work, this results in
undefined method `will_paginate' for #<#<Class:0x000000053674c8>:0x0000000535cd48>
So will_paginate works, but not the view helper. Am I missing something? I'm using slim templating if that makes any difference. Is there some syntax change I'm missing? The documentation is simple but unhelpful beyond this point. I looked into the source, and there does not seem to be any changes, but I cannot figure why it is inaccessible
And then on tangent, this messes with an association.
=> #instance.model_belonging_to_instance.create(:text=>'test')
TypeError: can't convert nil into Integer
from /home/qx/.rvm/gems/ruby-1.9.2-p180/gems/will_paginate-3.0.0/lib/will_paginate/page_number.rb:16:in `Integer'
etc etc et al
SOLUTION:
gemfile:
gem 'will_paginate', '~> 3.0.0' # removed this, :require=>'will_paginate/data_mapper'
intializer:
require 'will_paginate'
require 'will_paginate/data_mapper'
It shows up, but if not at the top of the template, I get a
stack level too deep
error I am unable to interpret
Don't use the :require option in the Gemfile, as you already figured out; instead require "will_paginate/data_mapper" somewhere in config/application.rb, for instance after the Bundler setup.
There is a similar question with an answer that indicates that auto-requiring here is the problem. See will_paginate undefined method. The Will_paginate gem appears to work though for the question and answer.
gem 'will_paginate', '~> 3.0.0', require: %w[
will_paginate
will_paginate/data_mapper
]

Resources