The rails params are not symbolized - ruby-on-rails-3

def log_experiments
=> 23: binding.pry
24: logger.debug "Experiment: 'navigation_location': '#{navigation_location_experiment}'"
25: end
[1] pry(#<MainController>)> params
=> {"sub_category1"=>"shoes", "controller"=>"main", "action"=>"index"}
[2] pry(#<MainController>)>
How and where can I check what is wrong here? by default the param keys should be symbolized...

Params use a special type of hash - hash with indifferent access. Elements of such hashes can be accessed both by symbols and string. For printing hash the default form is string.
Look at rails reference - http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html This is doc for rails 4.0, but the previous versions have the same

Related

how to test carrierwave fog google in rspec with setting up the configuration

I have below configuration and I wanted to write TC for it in ruby. I am new to ruby and wanted to understand how we can set the configuration of Fog to point to mock and use it in test-case.
class TestUploader < CarrierWave::Uploader::Base
storage :fog
def fog_credentials
{
:provider => 'google',
:google_project =>'my project',
:google_json_key_location =>'myCredentialFile.json'
}
end
def fog_provider
'fog/google'
end
def fog_directory
'{#bucket-name}'
end
def store_dir
when :File
"#{file.getpath}/file"
when :audio
"#{file.getpath}/audio"
else
p " Invalid file "
end
end
end
class TestModel
mount_uploader :images, TestUploader
end
Could someone please assist me from configuring to write and execute the unit test on it with few example. Any help would be really appreciated.
From the test I did, I got the following sample code working with Google Cloud Storage using Fog gem:
require "fog/google"
# Uncomment the following line if you want to use Mock
#Fog.mock!
# Bucket name
bucket = "an-existing-bucket"
# Timestamp used as sample string
test = Time.now.utc.strftime("%Y%m%d%H%M%S")
connection = Fog::Storage.new({
:provider => "Google",
:google_project => "your-project",
:google_json_key_location => "path-to-key.json",
})
# Lists objects in a bucket
puts connection.list_objects(bucket)
#Creates new object
connection.put_object(bucket, test, test)
puts "Object #{test} was created."
It works in production, but fails using mock mode with the following error:
`not_implemented': Contributions welcome! (Fog::Errors::MockNotImplemented)
It seems that it is not implemented as shown at the put_object method definition in the documentation.
Also, this is said in this GitHub issue:
Closing issue. 1.0.0 is out, and we have no more mocks for json backed objects.
Credentials
As shown in the Fog's documentation, to configure Google Credentials you have to them as follows:
connection = Fog::Storage.new({
:provider => 'Google',
:google_storage_access_key_id => YOUR_SECRET_ACCESS_KEY_ID,
:google_storage_secret_access_key => YOUR_SECRET_ACCESS_KEY
})
Mock
In the GitHub - Fog::Google documentation, there is also a minimal config to integrate Fog with Carrierwave.
In order to use the Cloud Storage mock, you can use the following line:
Fog.mock!
connection = Fog::Storage.new(config_hash)
Provider Specific Resources
In the provider documentation section, you will find links to provider specific documentation and examples.
Community supported providers can get assistance by filing Github Issues on the appropriate repository.
Provider
Documentation
Examples
Support Type
Google
Documentation
fog-google-examples
Community
In order to maximize the benefits of open source, you are encouraged submit bugs to Github Issues
In this GitHub example, you could find an implementation for Google Cloud Storage.
Class List
At the RubyGems documentation for fog-google, you can find the class definitions and parameters. For example, the list_objects method:
#list_objects(bucket, options = {}) ⇒ Google::Apis::StorageV1::Objects
Lists objects in a bucket matching some criteria.
Parameters:
bucket (String) — Name of bucket to list
options (Hash) (defaults to: {}) — Optional hash of options
Options Hash (options):
:delimiter (String) — Delimiter to collapse objects under to emulate a directory-like mode
:max_results (Integer) — Maximum number of results to retrieve
:page_token (String) — Token to select a particular page of results
:prefix (String) — String that an object must begin with in order to be returned
:projection ("full", "noAcl") — Set of properties to return (defaults to “noAcl”)
:versions (Boolean) — If true, lists all versions of an object as distinct results (defaults to False)
Returns:
(Google::Apis::StorageV1::Objects)

Problems regarding usage of Bodyguard library in Phoenix

We are trying to create a sample project using the Bodyguard library in Phoenix. We are just going to set some rules for users, as shown on the GitHub page, https://github.com/schrockwell/bodyguard. However, we are facing errors regarding the conn variable in lib\bg_web\controllers\post_controller.ex. We have uploaded our project in https://github.com/yashdani/bg. Please help us to identify the errors. Also, tell us what else we need to code in the project. We are really stuck, and we could not find any more information from the online documentation.
This is one of the errors:-
C:\Users\yashd\bg>mix phx.server
Compiling 18 files (.ex)
warning: variable "conn" does not exist and is being expanded to "conn()", please use parentheses to remove the ambiguity or change the variable name
lib/bg_web/controllers/post_controller.ex:6
== Compilation error in file lib/bg_web/controllers/post_controller.ex ==
** (CompileError) lib/bg_web/controllers/post_controller.ex:6: undefined function conn/0
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
(elixir) lib/kernel/parallel_compiler.ex:198: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6
You're missing the keyword do, instead of:
def update(conn, %{"id" => id, "post" => post_params})
should be:
def update(conn, %{"id" => id, "post" => post_params}) do

Model serilize hash turned from hash to string when saving object

ruby 2.3.3, rails 3.2.22.5
Hi. I'm using a serialized :logs, Hash in a User model, when saving the logs hash- afterwards it's being retrieved as string instead of Hash.
How it happen:
assign value to logs hash
save user object
now logs hash is a string..
So for user when assigning value to logs hash: user.logs[2] = 4, then saving
class User < ActiveRecord::Base
serialize :logs, Hash # in database it's a text type
end
An example in the rails console:
# rails console
test_user_id = 3
user = User.find(test_user_id)
user.logs = {}
user.save
user.logs # => {} # great
User.find(test_user_id).logs # => {} # great
# now trying to add value and save:
# 1. assign value to logs hash
user.logs[Time.now] = {:field_id=>6} # => {:field_id=>6}
# 2. save user object:
user.save
# 3. now logs hash is a string..
user.logs
#=> "---\n2017-07-03 19:33:34.938364000 +03:00:\n :field_id: 6\n"
# why it turned to string ?!?!
User.find(test_user_id).logs # same here:
# => "---\n2017-07-03 19:33:34.938364000 +03:00:\n :field_id: 6\n"
Any ideas?
Ok. so (As I understand it) Rails version: 3.2.22.5 is compatible with ruby 2.2.x but not ruby 2.3.x
So fixed it by reverting from ruby 2.3.3 to ruby 2.2.6

Backbone / Rails - build(params[...]) raises ActiveRecord::UnknownAttributeError

I am using backbone and trying to create a new object and I am running into this error. I thought rails would just ignore attributes that it doesn't care about. i.e. the authenticity token isnt trying to be added to my object.
My controller:
def create
page = Page.find(params[:page_id])
branch = page.page_branches.build(params[:page_branch])
branch.form = page.form
if branch.valid?
page.page_branches << branch
redirect_to(edit_page_path(page, :anchor => "branch-panel"))
else
raise "#{branch.errors.map}"
end
end
The Error:
Processing by PageBranchesController#create as JSON
Parameters: {"page_branch"=>{"next_page_id"=>"KS5ad82889e04e5806e0455d5a81e81a9511",
"description"=>"linking", "utf8"=>"", "authenticity_token"=>"", "id"=>nil,
"page_id"=>"KS000c29724a16-u-2TQMP57-gYm-U", "trigger_type"=>"Always",
"base_options"=>"AllowAnonymous;BASE",
"question_options"=>"KS000c29724a16CfC2TQUL1--gxG-U", "keyword_options"=>"",
"qualification"=>"", "commit"=>""}, "page_id"=>"KS000c29724a16-u-2TQMP57-gYm-U"}
WARNING: Can't mass-assign protected attributes: id
Completed 500 Internal Server Error in 239ms
ActiveRecord::UnknownAttributeError (unknown attribute: utf8):
app/controllers/page_branches_controller.rb:21:in `create'
Thanks to the response below:
I added the attr_accessible on my rails model:
attr_accessible :page_id, :page_name, :next_page_id, :next_page_name,
:description, :trigger_type, :internal_qualification,
:order, :form_id, :qualification
By doing that, I get the following warnings, but the build succeeds
WARNING: Can't mass-assign protected attributes: utf8, authenticity_token, id, base_options, question_options, keyword_options, commit
ActiveRecord mass assignment is gonna try to use every key/value pair in the hash is provided and raise an UnknownAttributeError when unknown attributes are supplied via mass assignment.
Maybe checking out this code can help to confirm what I'm saying.
I think you have two options:
To clean up the params[:page_branch] before use it in the mass assignment.
Modify the Backbone.YourModel.toJSON() to not send weird attributes to the server.

How can I add a link tag to the atom.builder feed generator?

In rails 3.0.9 (and maybe earlier) this code no longer works:
//feed.atom.builder
atom_feed :language => 'en-US' do |feed|
feed.title #title
feed.updated #updated
feed.link('href' => 'http://[REDACTED].superfeedr.com/', 'rel' => "hub")
...
end
The exact error is: ArgumentError: wrong number of arguments (1 for 2) with a stack trace of:
/Users/[REDACTED]/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/fileutils.rb:302:in `ln'
[GEM_ROOT]#global/gems/rake-0.8.7/lib/rake.rb:1094:in `link'
[GEM_ROOT]/gems/actionpack-3.0.9/lib/action_view/helpers/atom_feed_helper.rb:146:in `method_missing'
app/views/feeds/index.atom.builder:4:in `block in _app_views_feeds_index_atom_builder___2426096422608134746_70129604713820_3077995114801777171'
[GEM_ROOT]/gems/actionpack-3.0.9/lib/action_view/helpers/atom_feed_helper.rb:123:in `block in atom_feed'
…
This is important for me and to setup a superfeedr Pubsubhubbub as described here. I need to get a <link rel="hub" … > tag into the atom feed but feed.link no longer works like it used to due to the method being removed from atom_feed_helper.rb. How can I get this link tag to show up again?
I believe you used this gem which seems a bit old, and since Atom is just a flavor of XML, it may be easier to just write the feed yourself anyway, using the answer given there.