RoR: cannot get started with ezcrypto / ActiveCrypto - ruby-on-rails

I want to encrypt a field stored in an ActiveRecord table. A few helpful people pointed me towards ezcrypto which appears to be what I want. Especially interesting is ActiveCrypto, as described in ezcrypto.rubyforge.org/files/README_ACTIVE_CRYPTO.html
But I can't get it working. I've added
gem 'ezcrypto', '0.7.2'
to my Gemfile, run bundle install, and extended my User model with:
require 'ezcrypto'
class User < ActiveRecord::Base
...
keyholder
...
end
but that dies with undefined local variable or method 'keyholder'.
Ideas on how to get this working? TIA.

While I was digging around for an answer, I came upon attr_encrypted, which
is actively supported
does what I need
worked the first time
So I don't need an answer to the OP (unless you feel compelled to do so...). Hope this helps someone else.

Related

methods for debugging slow queries in active model serializers?

I am having difficulty optimizing my Active Model Serializers to avoid the n+1 problem. As per suggestions from their docs, I have attempted to eager load the associations which i thought were causing my query bottlenecks, but my serializers are still taking forever.
Obviously, i must be doing something wrong. My application is deeply nested with associations, so i guess I'm more interested in discovering a tool to unveil to me exactly WHICH associations are costing me. Right now, i am attaching a stack trace to every query run through the ActiveRecord
ActiveSupport::Notifications.subscribe("sql.active_record") do |_, _, _, _, details|
puts caller.join("\n")
puts "*" * 50
end
which gives me a ridiculous output because i am running so many queries to begin with, but, in addition, the stack traces are not helpful at identifying which serializer is at fault. It shows me which controller method was calling render, but then from there the stack trace simply prints methods from gems/active_model_serializers, which does not help me.
I am hoping to uncover a method of debugging that would be able to identify to me which serializers were at fault, that way i am not guessing at how to optimize my queries. Has anybody discovered anything like this? Thanks!
===================
UPDATE
Just so it is clear, i am already printing a query log, in addition to a stack trace. Unfortunately, with so many associations to keep track of, the query log is not exactly helpful at identifying the source of the query. It is guess work at best, and ineffective at the association scope i am dealing with.
I have abandoned the stack traces altogether, finding them to be totally unhelpful. Now, all i have printing are SQL logs, and i am manually sifting through them, trying to discover the source of the association.
The next method I will attempt (although i hate to resort to it) is commenting out associations until i see improvements in my query times. It will be more effective than trying to trace the source of the problem, but it will provide me no comfort in a production environment (where commenting out critical associations is not an option), so if anybody finds a solution that can help, I would still be very grateful.
I will continue to post updates as I move through this problem, as it may help many others in the future.
======================UPDATE 2
It turns out that commenting out associations in my serializer and reintroducing them one at a time, while ineffective in production, is an excellent way to debug in a local environment. I was able to drill down to the problem within a minute and correct it. Still, this is not an ideal solution. I would ideally like to be able to identify the problem from a log so that in production i could ascertain the issue without affecting the application's behavior.
The active_record_query_trace gem can do that.
Add the following to your Gemfile:
group :development do
gem 'active_record_query_trace'
end
Create an initializer such as config/initializers/active_record_query_trace.rb to enable the gem. If you want to customize how the gem behaves, you can add any combination of the options described in the docs to the initializer as well.
if Rails.env.development?
ActiveRecordQueryTrace.enabled = true
# Optional: other gem config options go here
end
Restart the Rails development server.
Easy way within any gems - is logging each string of code. For example, if you have
that code of serializer:
module Flats
class IndexSerializer < Api::V2::RealtyObjects::IndexSerializer
attributes(
:flat_number,
:entrance_number,
:floor_in_house,
:live_area,
:room_count,
:total_area,
)
end
end
add method which will be log time to your development.log on each attribute:
module Flats
class IndexSerializer < Api::V2::RealtyObjects::IndexSerializer
attribute_list = %i[
flat_number
entrance_number
floor_in_house
live_area
room_count
total_area
]
attributes(*attribute_list)
def logger(name, value)
Rails.logger.debug name, value, "#{Time.now.strftime('%M:%S--%N')}"
end
attribute_list.each do |attribute_name|
define_method attribute_name do |value|
logger(attribute_name, value)
super
end
end
end
end

Conflict between Rails Admin and Impressionist gems

I'm using the latest version of the Impressionist and Rails Admin gems, and wondering if anyone could shed some light on an annoying conflict I'm experiencing. The problem is roughly documented here - https://github.com/sferik/rails_admin/issues/1315, yet the vaguely described solution is not working for me. When I have the line is_impressionable in my Listing model, I get an error when starting my Rails server with rails s:
...rvm/gems/ruby-2.0.0-p247/gems/activerecord-4.0.2/lib/active_record/dynamic_matchers.rb:22:in `method_missing': undefined local variable or method `is_impressionable' for Listing(no database connection):Class (NameError)
If I first start the server, and then add the 'is_impressionable' line, everything works fine, so the problem only occurs during initialization. I don't fully understand the initialization process, so am not sure how to go about getting this to work.
I have tried moving all my rails_admin model configuration options to their respective models, rather than in the initializer, which had no effect. I also have the following line in my initializer:
config.included_models = [Listing,ListingImage,AllOtherModelsHere...]
I have tried adding single quotes around these model names, which results in the following errors, as described in the github issue here
[RailsAdmin] Could not load model Listing, assuming model is non existing. (undefined local variable or method `is_impressionable' for Listing(no database connection):Class)
Any ideas what else I can try to make these gems work together? I don't want to have to remove the is_impressionable line every time I want to restart the server or generate a migration...
Not sure if the same issue that I had but yet I will post what worked for me just in case someone struggles with this too:
Im on a ruby 2.1.5 project with rails 4.2.0 and among other gems I'm using rails admin.
I run into several weird problems trying to set this up. For instance if I added the is_impressionable call within one of my models for some reason the execution of that file stopped there and I started getting weird errors like any method declared below the is_impressionable failed with undefined error.
So what I end up doing was:
class MyModel < ActiveRecord::Base
include Impressionist::IsImpressionable
is_impressionable
end
So this solved my issue and now i can access #my_model_instance.impression_count as expected.
I changed every occurrence of Klass to 'Klass'.constantize in initializer.

Problems Implementing ActiveModel Dirty Rails 3.2.8

I want to check when attributes on a model have changed. I have attempted to check values != the value on the form before doing a save but that code is really ugly and is not working well at times. Same with using update_column which does not do the validations in my model class. If I use update_attributes without doing something else I will not be able to check when a field has been updated from my understanding. From my web research on Stack Overflow and other sites it appears that using ActiveModel Dirty is the way to go.
I have looked at this: http://api.rubyonrails.org/classes/ActiveModel/Dirty.html
My hope is to use this to check if boolean flags changed on a model after using update_attributes. I attempted to do the minimum implementation as described in the included link. I added the following to my ActiveRecord class:
include ActiveModel::Dirty
define_attribute_methods [:admin]
I tried adding the three attributes I wanted to keep track of. I started with just one attribute to see if I could get it working. I received the following error when I ran an rspec test. Once I removed the argument I had no errors.
Exception encountered: #<ArgumentError: wrong number of arguments (1 for 0)>
After I removed the argument I decided to include similar methods in my model using admin instead of name. Other Rspec tests broke on the save method. However I feel the problem is with how I am implementing ActiveModel Dirty.
I have read on other Stack Overflow posts where commenters stated that this was included in 3.2.8 so I upgraded from 3.2.6 to 3.2.8. I did not understand what that meant so after getting errors I decide just to leave the include ActiveModel::Dirty statement and try to use admin_changed? Of course it did not work.
I have not been able to find anything about how to initially set things up for this other than the link I included here. All the other research I have found assumes that the initial setup was correct and that updating to the current stable version of Rails would take care of their problems.
Any help would be appreciated on how to implement this. Doing the minimal implementation as stated in the link is not working. Maybe there is something else I am missing.
The problem appears to be that ActiveRecord redefines the define_attribute_methods method to accept 0 arguments (because ActiveRecord automatically creates attribute methods for every column in the database table): https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods.rb#L23
This overrides the define_attribute_methods method provided by ActiveModel: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/attribute_methods.rb#L240
Solution:
I figured out a solution that worked for me...
Save this file as lib/active_record/nonpersisted_attribute_methods.rb: https://gist.github.com/4600209
Then you can do something like this:
require 'active_record/nonpersisted_attribute_methods'
class Foo < ActiveRecord::Base
include ActiveRecord::NonPersistedAttributeMethods
define_nonpersisted_attribute_methods [:bar]
end
foo = Foo.new
foo.bar = 3
foo.bar_changed? # => true
foo.bar_was # => nil
foo.bar_change # => [nil, 3]
foo.changes[:bar] # => [nil, 3]
However, it looks like we get a warning when we do it this way:
DEPRECATION WARNING: You're trying to create an attribute `bar'. Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer` etc.
So I don't know if this approach will break or be harder in Rails 4...
See also:
Track dirty for not-persisted attribute in an ActiveRecord object in rails
https://github.com/adzap/validates_timeliness/issues/73
Try adding adding =, like this:
define_attribute_methods = [:admin]
That change worked for me. Not sure if it has something to do with this?

Cannot find gem in controller

I'm sure this is an easy question but I'm having a hard time figuring out what to Google.
I'm trying to use the library ChunkyPNG.
I added it to my Gemfile and did a bundle install.
bundle list | grep "chunky"
* chunky_png (1.2.5)
So far so good.
I try using it in my controller:
image = ChunkyPNG::Canvas.from_data_url(params[:data]).to_image
(The docs for this method are available here)
It results in the following error:
NameError in MyController#create
uninitialized constant MyController::ChunkyPNG
Why is prepending the controller namespace? I imagine that's what is causing the error.
Otherwise, it means that ChunkyPNG is not install (and it clearly is).
Am I not able to use this gem upfront without writing some sort of rails plugin to wrap around it?
Thanks
EDIT:
Question has been answered, see #apneadiving's comment
In your controller, or somewhere else in the app do:
require 'chunky_png'

"undefined method `fixtures' for ActiveSupport::TestCase:Class" while testing with Rails 3.1

I'm writing tests for a Gem and after a couple of hours trying to get rid of this, decided to look around - and to my surprise, there's not a single reference to it on Google (apart from one on mongoid, where people simply ignored it).
So, the problem is simple: I have this block on my test initialization:
class ActiveSupport::TestCase
fixtures :all
end
but the tests fail to execute:
`<class:TestCase>': undefined method `fixtures' for ActiveSupport::TestCase:Class (NoMethodError)
The gem depends on Rails 3 and every dependency is checked & double-checked. The code is on github, in case anyone wants to check (https://github.com/herval/acts_as_recommendable)
I'm out of ideas. Anyone share a light?
I'm not sure, but it seems that fixtures cannot be used with mongoid.
Take a look at this for further details:
https://groups.google.com/forum/?fromgroups=#!topic/mongoid/tqlx3j88Lqw
It's been a long time since I used Rails' built in testing, so take this with a grain of salt. I'm guessing that the actual ActiveSupport::TestCase class hasn't actually been loaded before the initializer is being reached.
It might be enough to just add require 'test_help' at the top of the initializer.

Resources