vendredi 31 juillet 2015

Hash and values

I came across this Ruby script:

frequency = Hash.new(0)
...
...
file.read.downcase.scan(/\b[a-z]{4,20}\b/){|word| frequency[word] =
frequency[word]+1}

The point I couldn't understand is frequency[word] = frequency[word]+1

Wouldn't frequency[word] give me the word matched? How can we add it to 1?

Mongoid, setting custom accessor field in mongoid-history gem

I'm adding mongoid-history gem to my project.

According to guide in github, when I add Userstamp to my tracker it creates created_by field with accessor called creator.

They have written that I can rename it via gem config.

How to rename this field?

Rails_admin show child models fields in parents show page

I have Item model and I have ItemImage child model which is embedded inside of its parent.

When I open single Items page in rails_admin, it shows all of its children like this:

ItemImage #55b766556c656e12d0ac0000, ItemImage #55b766556c656e12d0ad0000, and ItemImage #55b766566c656e12d0ae0000

How to make rails_admin to show all of its children fields inside parents page? Is it possible to show them as table?

I'm using Mongoid.

How best to represent roles in the DB of a rails app?

I'm building authorization in my app and have three roles:

  • User
  • Moderator
  • Admin

What's the best way to represent this in Rails? I've thought about adding the following boolean fields to my user's table:

  • is_user
  • is_moderator
  • is_admin

And then creating is_user?, etc functions in the User model.

A user can have multiple roles (can be all three).

Can't Compile LESS to CSS with LESS2CSS Plugin on Sublime Text 3 Mac

I am using Sublime Text 3 on Mac OS Yosemite. I want to use LESS2CSS package but it not working. Here are the errors it gives:

WARNING] Please install gem 'therubyracer' to use Less.
/Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require': cannot load such file -- v8 (LoadError)
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/java_script/v8_context.rb:2:in `<top (required)>'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/java_script.rb:9:in `default_context_wrapper'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/java_script.rb:17:in `context_wrapper'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less/loader.rb:13:in `initialize'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less.rb:14:in `new'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less.rb:14:in `<module:Less>'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/lib/less.rb:9:in `<top (required)>'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Site/2.0.0/rubygems/core_ext/kernel_require.rb:54:in `require'
    from /Library/Ruby/Gems/2.0.0/gems/less-2.6.0/bin/lessc:3:in `<top (required)>'
    from /usr/bin/lessc:23:in `load'
    from /usr/bin/lessc:23:in `<main>'

I've installed Node.js and installed less, but it is still not working.

Cannot find my mistake with jQuery autocomplete and Rails 4

router

  resources :pcps  do
    collection do
      get 'autocomplete'
    end
  end

controller

def autocomplete
    @pcps = Pcp.order(:last).where("last like ?", "%#{params[:term]}%")
    render json: @pcps.map(&:full_name)
end

View

= f.text_field :pcp, data: {autocomplete_source:  '/pcps/autocomplete'}

Coffee script

This code works

jQuery ->
  $('#sched_pcp').autocomplete
    source: ["Atest", "Btest","Ctest","Dtest","Btest1","Btest2"]

This code does not work.

jQuery ->
  $('#sched_pcp').autocomplete
    source: $('#sched_pcp').data('autocomplete-source')

I am using ruby 2.2 and rails 4.2 The url '/pcps/autocomplete' returns the correct data. Can someone help me see my mistake please? or maybe give me an idea how to debug it.

How do I seed a unique record ONLY via my seeds.db?

I have the following code in my seeds.rb used to create a record in my basic Rails app via seeding.

Post.create( title: "Unique Title!", body: "this is the most amazingly unique post body ever!" )

When running the rake db:seed command, it obviously seeds the db with this data. My question is how do I add a check or safeguard in the code so that it only enters that once, i.e. as a unique? If I rerun rake db:seed, I don't want add that same entry again.

Thanks

Ruby HTTPS Post issue

I have two codes (variable info masked intentionally), the first one I receive the response with 200 code return, but second one I get 403 forbidden, any idea?

def get_token()
    http = Net::HTTP.new(server, 443)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?

    #path(a.k.a) ->http://ift.tt/1DXPdIx'
    path = '/rest/fastlogin/v1.0?app_key=' + app_key + '&username=%2B' + username + '&format=json'
    puts path

    headers = {'Content-Type'=> 'application/x-www-form-urlencoded', 'Authorization' => password }

    resp, data = http.post(path, data, headers)

    puts 'Code = ' + resp.code
    puts 'Message = ' + resp.message

    resp.each {|key, val| puts key + ' = ' + val}
    puts data
    puts JSON.parse(resp.body)["access_token"]

    result = {}

    result["code"] = resp.code
    result["token"] = JSON.parse(resp.body)["access_token"]

    print  result

    return result
end



def get_token1()
    path = '/rest/fastlogin/v1.0?app_key=' + app_key + '&username=%2B' + username + '&format=json'

    uri = URI.parse('https://' + server + path)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl?

    req = Net::HTTP::Post.new(uri.path)
    req["Authorization"] = password

    puts uri.host
    puts uri.path
    puts uri.port
    resp,data = http.request(req)
    print resp 
end

No route matches [POST] - Rails destroy

I'm new to RoR and still don't have enough experience on solving the different errors that may appear to me. In this case I'm designing a blog where I can post articles. More specifically, my problem is related to deleting these articles.

As far as I know, writing:

resources :articles

in the routes file is an alternative for writing:

get "/articles"            #index
post "/articles"           #create
delete "/articles/:id"     #delete
get "/articles/:id"        #show
get "/articles/new"        #new
get "/articles/:id/edit"   #edit
patch "/articles/:id"      #update
put "/articles/:id"        #update

When I try to delete an article I get the following error:

No route matches [POST] "/articles/1"

The code I wrote was:

View

<% @articles.each do |art| %>
    <%= art.title %>
    <div>
        <%= art.body %> - <%= link_to "Delete", art, method: :delete %>
    </div>
<% end %>

Controller

def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to articles_path       
end

I can't see what am I missing. Thanks in advanced.

Merit doesn't add points to user after create action

I've used this instructions for simply add score when a user creates a "solucion" (which is a kind of "answer" to a micropost). I have added the has_merit line to user.rb (user model).

I want to display the user points earned for that action at the show view. show.html.erb (for solucion):

<h2><span class="red"><%= current_user.points %></span><br>Points</br></h2>

It displays 0 points...

point_rules.rb:

module Merit
  class PointRules
   include Merit::PointRulesMethods

   def initialize
    score 5, on: 'solucions#create'
   end
  end
end

When I create a solucion with the current_user (already saving the user_id index and identifier to solucion), This is what my rails server output shows...

Direct link to github gist:

http://ift.tt/1DXPevP

Embed:

<script src="http://ift.tt/1SquLMf"></script>

Illformed requirement error when installing gems

I'm getting the following error whenever I try to install any gem (sass as an example)

ERROR:  While executing gem ... (Gem::Requirement::BadRequirementError)
    Illformed requirement ["sass"]

I'm running Windows 10 Pro (not activated yet) so I was wondering if this could be a reason as to why this is happening? I've tried using the 32 bit version of Ruby 2.2.2 as well and it gives the same error. How do I fix this and what could be the reason I get it? Any help is appreciated, thanks!

Kill process launched via thread

I have a headless application that uses sockets for communication. When launched, it remains active until sent a message telling it to quit (or it crashes, or is killed).

When unit testing this application using Ruby, I need to launch the process, interact with it (via sockets), and then kill it.

I thought I could do this using this pattern:

class TestServer < MiniTest::Unit::TestCase
  def setup
    @thread = Thread.new{ `#{MY_COMMAND}` }
  end

  def test_aaa
    # my test code
  end

  def teardown
    @thread.kill if @thread
  end
end

However, that teardown code kills the thread but does not kill the process launched by it.

How can I launch the process in a way that:

  1. Allows it to run in the background (immediately returns control to my Ruby test harness)
  2. Allows me to force kill the process later on, if need be.

I happen to be developing on OS X, but if possible I'd appreciate a generic solution that works across all OS where Ruby runs.

Connecting to background EventMachine application for unit testing

I am writing a headless Ruby application using EventMachine that communicates over sockets. I want to write some unit tests for this app. This means that my Ruby test script needs to launch that app in the background, perform socket communication with it, and then close that process.

This code fails. The socket connection is refused.

require 'socket'
PORT = 7331
CMD = File.expand_path("../../bin/rb3jay",__FILE__)
@thread = Thread.new{ `#{CMD} -D --port #{PORT}` }
@socket = TCPSocket.open('localhost', PORT)
#=> Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 7331

If I inject a 2 second delay before attempting the socket connection, it works as desired:

@thread = Thread.new{ `#{CMD} -D --port #{PORT}` }
sleep 2
@socket = TCPSocket.open('localhost', PORT)

This seems a gross hack. Maybe 2 seconds is long enough for my machine, but too short somewhere else. How should I correctly:

  • Launch my EventMachine application in the background
  • Create a socket connection to it as soon as it is ready
  • After my tests are done, ensure that the socket is closed and that I kill the background application

Recursive SQL using Rails 4 (modeling)

I read a tutorial, but I did not understand properly. I will quote it here and present the problem that seek to solve.

Tutorial

My problem: I'm doing a forum that can have various categories and subcategories. Then decide to use SQL Recursive PostgreSQL to facilitate me and not pollute my db with unnecessary tables. Suppose I have a table categories, and it has the categories_id field. Then the model would look something like this:

  attr_accessible :parent

  belongs_to :parent, :class_name => "Category"
  has_many :children, :class_name => "Category", :foreign_key => 'categories_id'

  scope :top_level, where(:categories_id => nil)

1- I did not understand fully if parent and children are a field in the table or not. 2- Why did he have to create a attr_accessible :parent? 3- Why the creation of scope?

Thanks,

Command "rails s" not working?

 C:\Users\Sprache\Sites\simple_cms>rails -v
Rails 4.2.3

C:\Users\Sprache\Sites\simple_cms>bundle list
Gems included by the bundle:
* actionmailer (4.2.3)
* actionpack (4.2.3)
* actionview (4.2.3)
* activejob (4.2.3)
* activemodel (4.2.3)
* activerecord (4.2.3)
* activesupport (4.2.3)
* arel (6.0.2)
* binding_of_caller (0.7.2)
* builder (3.2.2)
* bundler (1.10.6)
* byebug (5.0.0)
* coffee-rails (4.1.0)
* coffee-script (2.4.1)
* coffee-script-source (1.9.1.1)
* columnize (0.9.0)
* debug_inspector (0.0.2)
* erubis (2.7.0)
* execjs (2.5.2)
* globalid (0.3.5)
* i18n (0.7.0)
* jbuilder (2.3.1)
* jquery-rails (4.0.4)
* json (1.8.3)
* loofah (2.0.2)
* mail (2.6.3)
* mime-types (2.6.1)
* mini_portile (0.6.2)
* minitest (5.7.0)
* multi_json (1.11.2)
* mysql2 (0.3.19)
* nokogiri (1.6.6.2)
* rack (1.6.4)
* rack-test (0.6.3)
* rails (4.2.3)
* rails-deprecated_sanitizer (1.0.3)
* rails-dom-testing (1.0.6)
* rails-html-sanitizer (1.0.2)
* railties (4.2.3)
* rake (10.4.2)
* rdoc (4.2.0)
* sass (3.4.16)
* sass-rails (5.0.3)
* sdoc (0.4.1)
* sprockets (3.2.0)
* sprockets-rails (2.3.2)
* thor (0.19.1)
* thread_safe (0.3.5)
* tilt (1.4.1)
* turbolinks (2.5.3)
* tzinfo (1.2.2)
* tzinfo-data (1.2015.5)
* uglifier (2.7.1)
* web-console (2.2.1)

Hey all! Following this course here on lynda, and I'm having a wee issue.

So I've got my new project setup and I'm in the root folder.

I try to run

rails s

and

rails server

and

bundle exec rails server

and I keep getting the response


C:\Users\Sprache\Sites\simple_cms>rails s C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32/lib/nokogiri .rb:29:in require': cannot load such file -- nokogiri/nokogiri (LoadError) from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32 /lib/nokogiri.rb:29:inrescue in ' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.6.2-x64-mingw32 /lib/nokogiri.rb:25:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.2/lib/loofah.rb:3 :inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.2/lib/loofah.rb:3 :in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l ib/rails-html-sanitizer.rb:2:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l ib/rails-html-sanitizer.rb:2:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/sanitize_helper.rb:3:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/sanitize_helper.rb:3:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:32:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:29:in <module:Helpers>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:6:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/text_helper.rb:4:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:18:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:14:in <module:Helpers>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:8:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_tag_helper.rb:6:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_helper.rb:4:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers/form_helper.rb:4:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers.rb:50:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers.rb:4:in <module:ActionView>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.3/lib/action_ view/helpers.rb:3:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:7:in <module:LegacyAssetTagHelper>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:6:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:4:in <module:Sprockets>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/legacy_asset_tag_helper.rb:3:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:45:in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:45:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:7:in <module:Rails>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:6:in' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/rails/helper.rb:5:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/railtie.rb:6:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.3.2/lib/sp rockets/railtie.rb:6:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils/railtie.rb:3:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils/railtie.rb:3:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils.rb:11:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass/ra ils.rb:11:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass-ra ils.rb:1:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.3/lib/sass-ra ils.rb:1:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:76:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:76:in block (2 levels) in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:72:ineach' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:72:in block in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:61:ineach' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler/r untime.rb:61:in require' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.10.6/lib/bundler.r b:134:inrequire' from C:/Users/Sprache/Sites/simple_cms/config/application.rb:7:in <top (required)>' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:78:inrequire' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:78:in block in server' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:75:intap' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:75:in server' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands/commands_tasks.rb:39:inrun_command!' from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/com mands.rb:17:in <top (required)>' from bin/rails:4:inrequire' from bin/rails:4:in `'


What do these things mean and what do I do?

Grazie a tutti!

getting No route matches [POST] "/login/log_in"

im using gem parse-ruby-client and im trying to create a login. and when the login is successful then i want to go to a welcome#index

here is my login_controller.rb

class LoginController < ApplicationController
  def index

  end
  def log_in
    @user = Parse::User.authenticate(params[:user][:username], params[:user][:password])
  end
end

index.html.erb

<div class="Log_in_Form">
  <h4><center>Log in with your existing "app_name" account</center></h4>
  <%= form_for(:user, :url => {:controller => 'login', :action => 'log_in'}) do |f| %>
    <center><p> Username:</br> <%= f.text_field :username%> </p></center>
    <center><p> Password:</br> <%= f.password_field :password%></p></center>
    <center><h4><%= f.submit :Login %></h4></center>
  <% end %>
</div>

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  root 'login#index'  

  get 'login/log_in' => 'login#log_in'
end

How to use the create method for a many:many through relationship

User and Organization have a many-to-many association through Relationship.

The Relationship model, amongst other things, specifies whether the User is a member of the Organization (member boolean).

If a new Organization together with a new User related to that Organization needs to be created I currently do the following:

Organization.create!(name: "name", ...).users.create(email: "email@email.com",...)

However, this does not yet set the member boolean in the Relationship model to true.

Is there a way to include this in the above command? Or is this only possible separately from creating the user and organization record? Because then it would require relatively a lot of code and seems a bit inefficient to add after the previous create line:

@user = User.find_by(username: username)
@organization = Organization.find_by(name: name)
@relationship = @organization.relationships.find(@user)
@relationship.update_attributes(member: true)

Travis CI Build doesn't install gems for JRuby platform

I have a travis build set up for my project that also run on JRuby. I mention the activerecord-jdbcsqlite3-adapter gem in the Gemfile for the :jruby platform:

platforms :jruby do
  gem "activerecord-jdbcsqlite3-adapter"
end

but the build still always fails with the message LoadError: Please install the sqlite3 adapter:gem install activerecord-sqlite3-adapter(sqlite3 is not part of the bundle. Add it to Gemfile.) and the gem actually doesn't get installed.

The project is open source at http://ift.tt/1LVPBO8, the build is at http://ift.tt/1I97Z3q.

Breaking a parameter and save the items separately

I need to save items separately coming from a form of a text field, but my code is saving these items duplicate form.

My controller

def create

  @answer_option = AnswerOption.break_options(answer_option_params)
  @answer_option = AnswerOption.new(answer_option_params)

  respond_to do |format|
    if @answer_option.save
      format.html { redirect_to @answer_option, notice: 'Answer option was successfully created.' }
      format.json { render :show, status: :created, location: @answer_option }
    else
      format.html { render :new }
      format.json { render json: @answer_option.errors, status: :unprocessable_entity }
    end
  end
end

My model

class AnswerOption < ActiveRecord::Base
  belongs_to :question

  def self.break_options(var)
    ugly_answers = var[:content].split /[\r\n]+/
    ugly_answers.each do |answer|
      AnswerOption.create!(content: answer)
    end
  end

end

Thanks!

I'm trying to create a new file within a folder in my rails application

I'm following along with the 'Rails Crash Course' book and it is telling me to create a file within a folder in a rails application that already exists.

I've searched the whole book but I can't find the instructions to create a file. I feel like this should be easy but I have searched online and cannot find a straight answer.

Here's an example: Create a new file named app/views/posts/index.html.erb and add the following code...

Here's another: Create the file app/views/text_posts/_text_post.html.erb and open for editing...

Anyone got the solution?

Oauth with sinatra.

So I have been learning how to program over the last couple of months. Prior to 2 months ago I didn't know anything. So that you know where I am at I feel comfortable with JS/ruby, ajax, sinatra, and building a full CRUD application and I've mainly used bootstrap for front end. I feel that I understand the process of oauth from (client_id, client_secret, callback, tokens, etc). I was wondering if someone could give me a breakdown of what is happening here in this code. From the view, controller (routes), and the before helper method. I'm not too sure how net/http is working. Any help would be appreciated.

require "rubygems"
require "sinatra"

require "net/http"
require "net/https"
require "cgi"

require "json"

enable :sessions

before do
  @client_id = "YOUR-CLIENT-ID-HERE"
  @client_secret = "YOUR-CLIENT-SECRET-HERE"

  session[:oauth] ||= {}
end

get "/" do
  if session[:oauth][:access_token].nil?
    erb :start
  else
    http = Net::HTTP.new "graph.facebook.com", 443
    request = Net::HTTP::Get.new "/me?access_token=#{session[:oauth][:access_token]}"
    http.use_ssl = true
    response = http.request request
    @json = JSON.parse(response.body)

    erb :ready
  end
end

get "/request" do
  redirect "http://ift.tt/1DXil2B"
end

get "/callback" do
  session[:oauth][:code] = params[:code]

  http = Net::HTTP.new "graph.facebook.com", 443
  request = Net::HTTP::Get.new "/oauth/access_token?client_id=#{@client_id}&redirect_uri=http://localhost:4567/callback&client_secret=#{@client_secret}&code=#{session[:oauth][:code]}"
  http.use_ssl = true
  response = http.request request

  session[:oauth][:access_token] = CGI.parse(response.body)["access_token"][0]
  redirect "/"
end

get "/logout" do
  session[:oauth] = {}
  redirect "/"
end

enable :inline_templates

__END__

@@ start
<a href="/request">Let's see who you are</a>.

@@ ready
<img style="padding: 20px" src="http://ift.tt/1DXiinb @json["id"] %>/picture" />
<br />
Hello, <%= @json["name"] %>! <a href="/logout">Logout</a>.

Normalizing raw text in different formats to create objects in Ruby

I have three text files with the exact same type of information but with different delimiters. One is a CSV, one uses spaces as delimiters, and the last one uses | (pipe) as the delimiter. The delimiters are different, but each row in all of the files has exactly the same format. So in the pipe-delimited file, the format is FirstName | LastName | DOB | City | State | ZIP (there is a space before and after each pipe). The other two files use the exact same order but with the other delimiters. All rows are unique. The files do not have headers.

I want to go through all of these files and create an instance of my Person object for each row. The class looks like this:

class Person
  attr_reader :first_name, :last_name, :d_o_b, :city, :state, :zip

  def initialize(first_name, last_name, ...)
    @first_name = first_name
    @last_name = last_name
    ...
  end

  ...

  etc.

end

I want to parse this data and create the objects in the cleanest and most readable way -- performance/scaling/etc. are unimportant here. What approach would be best for doing this? My initial idea is to convert all of the files to CSV somehow (perhaps with a gsub), then make a nested array from this data, and then iterate over the array to create the objects, but I am looking for any possible better/cleaner ideas.

Dokku push error

After several try to push an app to a dokku instance . i keep receiving this error.I've already search both github and stackoverflow for similar issues but none of them resolve it.I have check my css folders and files for any issue .Unable to pinpoint where the error coming from. If anybody have an idea to resolve it . please share.

 NoMethodError: undefined method `[]' for nil:NilClass                                                                                                                                 
       (in /tmp/build/app/assets/stylesheets/application.css)                                                                                                                                
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sprockets-2.12.4/lib/sprockets/sass_functions.rb:63:in `sprockets_context'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sprockets-2.12.4/lib/sprockets/sass_functions.rb:14:in `image_path'                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/funcall.rb:113:in `_perform'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/node.rb:40:in `perform'                                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `block in _perform'                                                                                
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `map'                                                                                              
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/list.rb:71:in `_perform'                                                                                         
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/script/node.rb:40:in `perform'                                                                                          
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:298:in `visit_prop'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `visit'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:100:in `visit'                                                                                 
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `map'                                                                                       
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `visit_children'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:109:in `block in visit_children'                                                               
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:121:in `with_environment'                                                                      
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:108:in `visit_children'                                                                        
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `block in visit'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:320:in `visit_rule'                                                                            
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:37:in `visit'                                                                                     
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/perform.rb:100:in `visit'                                                                                 
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `block in visit_children'                                                                   
       /tmp/build/vendor/bundle/ruby/2.0.0/gems/sass-3.2.19/lib/sass/tree/visitors/base.rb:53:in `map' 

Getting around devise authentication requirement

I'm trying to not require authentication for my reports view action. However when I try to use the devise method skip_before_action or skip_before_filter, it will still revert me back to the login page.

Here is my application controller.

  class ApplicationController < ActionController::Base

  acts_as_token_authentication_handler_for User

  protect_from_forgery with: :exception
  before_action :configure_permitted_parameters, if: :devise_controller?
  before_action :require_user

  layout :check_layout

  protected

  def check_layout
    devise_controller? ? 'legacy' : nil
  end

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :username
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email) }
  end

  private

  def require_user
    authenticate_user!
  end
end

Here is my reports controller

    class ReportsController < ApplicationController

  skip_before_action :require_user, only: [:view]
  skip_before_action :verify_authenticity_token, only: [:transition]
  before_action :check_params, only: [:transition]
  before_action :set_report, only: [:show, :edit, :update, :destroy, :draft, :copy_edit, :review_and_approve, :revise, :approve, :archive, :mail_merge, :draft_from_queue]

end

How do I do I go about not requiring authentication for the report view action?

SQLite claims duplicate rows on insert whereas none can be found

I have a table in a SQLite database created with the code below. Note the compound primary key:

db.create_table(:person_hash) do
  Integer :person_id
  Bignum :hash // MD5 hash in hex stored as numeric: hash.to_i(16)
  primary_key [:person_id, :hash]
end

This table has some rows already:

puts db[:person_hash].where(:person_id => 285577).all
# {:person_id=>285577, :hash=>306607097659338192312932577746542919680}

Now, when I try to insert this:

db[:person_hash].insert({:person_id=>285577, :hash=>306607097659338206333361532286405644297})

I get this:

SQLite3::ConstraintException: columns person_id, hash are not unique (Sequel::DatabaseError)

If the row does not already exist in the table, how can it be a duplicate?

I tried inserting another hash for the same person ID instead, and it worked without problems.

How to detect untested ruby files?

I recently started working on a large Rails application. Simplecov says test coverage is above 90%. Very good.

However now and again I discover files that are not even loaded by the test suite. These files are actually used in production but for some reason nobody cared enough to even write the simplest test about them. As a result they are not counted in the coverage metrics.

It worries me since there is an unknown amount of code that is likely to break in prod without us noticing.

Am I the only one to have this problem? Is there a well-known solution? Can we have coverage metrics for files not loaded?

Ruby oauth2 gem - how to override the token refresh URL for refresh! method?

I am using the ruby oauth2 gem, but for Adobe echosign implementation, the token refresh URL (/oauth/refresh) is different from the one the the gem expects(/oauth/token).

Is there an elegant way to do this (without changing the gem code to add the URL parameter there) ?

Ruby IDE similar to Visual Studio?

I want to know if there's an IDE for Ruby who's similar to Visual Studio where there is a toolbox and we can do Drag-and-drop tools from the box and place them on a windows form, I tried IronRuby and Sapphire for my Visual Studio 2012 and tried with Visual Studio 2010 too, but it's not working. When I want to launch the application in Visual Studio 2010 or Visual Studio 2012, I've got the error : Flash Forms Compiler failed with exit code 6

Rectangle intersection in Ruby

So I'm trying to understand this program but I'm having some difficulty. What I don't get in particular is the part with x_min, y_min, x_max, y_max. I get the the program passes through 2 rectangles with the bottom left and top right coordinate points. But where do the array indices come from? [0][0] , [1][1], etc? I'm confused about what's happening here exactly so if someone could break this down for me like I'm 5 that'd be awesome. I saw this particular question was answered before on here but I didn't get the explanation. Thanks.

    # Write a function, `rec_intersection(rect1, rect2)` and returns the
# intersection of the two.
#
# Rectangles are represented as a pair of coordinate-pairs: the
# bottom-left and top-right coordinates (given in `[x, y]` notation).
#
# Hint: You can calculate the left-most x coordinate of the
# intersection by taking the maximum of the left-most x coordinate of
# each rectangle. Likewise, you can calculate the top-most y
# coordinate of the intersection by taking the minimum of the top most
# y coordinate of each rectangle.
#
# Difficulty: 4/5
def rec_intersection(rect1, rect2)

x_min = [rect1[0][0], rect2[0][0]].max
x_max = [rect1[1][0], rect2[1][0]].min

y_min = [rect1[0][1], rect2[0][1]].max
y_max = [rect1[1][1], rect2[1][1]].min

return nil if ((x_max < x_min) || (y_max < y_min))
return [[x_min, y_min], [x_max, y_max]]
end

puts rec_intersection(
      [[0, 0], [2, 1]],
      [[1, 0], [3, 1]]
    ) == [[1, 0], [2, 1]]

puts rec_intersection(
      [[1, 1], [2, 2]],
      [[0, 0], [5, 5]]
    ) == [[1, 1], [2, 2]]


puts rec_intersection(
      [[1, 1], [2, 2]],
      [[4, 4], [5, 5]]
    ) == nil

puts rec_intersection(
      [[1, 1], [5, 4]],
      [[2, 2], [3, 5]]
    ) == [[2, 2], [3, 4]]

How many rails instances does delayed job initialize if running multiple pools

I'm running Delayed Job with the pool option like:

bundle exec bin/delayed_job -m --pool=queue1 --pool=queue2 start

Will this spawn one OR multiple rails environments? (ie: will it spawn one environment for all the pools or will every pool gets its own rails environment)?

When testing locally it seemed to only spawn one rails environment for all the pools.

But I want to confirm this 100% (esp on production).

I tried using commands like these to see what the DJ processes were actually pointing to:

ps aux, lsof, pstree

Anyone know for sure how this works, or any easy way to find out? I started digging through the source code but figured someone prob knows a quicker way.

Thanks!

How does forwardable work in this context?

I'm following along a tutorial to make a Rack-based app:

require 'forwardable'
module Eldr
  class App
    class << self
      extend Forwardable
      attr_accessor :builder
      def_delegators :builder, :map, :use

      def builder
        @builder ||= Rack::Builder.new
      end
    end
  end
end

I know this will sound really noobish, but I'm new to Ruby metaprogramming:

  • What exactly is the class << self? Doesnt that mean App < App?
  • What exactly is Forwardable? I looked it up but I'm sad to say I don't understand it still
  • Why is app extending Forwardable and what is Forwardable?

I know that the goal is to make this bit behave like Rack::Builder; Just trying to wrap my head around this one.

Thanks in advance.

Strange result from Ruby string to string less than comparison

So I have two strings '5' and '12'. In Ruby (ruby 2.0.0p598 (2014-11-13 revision 48408)) I want to do a comparison on these two to see which is less than the other. If I do '5' <= '12' I get false as a result. Why?

Is it possible to execute a method after sending a response back to the browser in Rails?

I'm trying to run an action after I send a response back to the client in Rails. Is it possible to do this without background workers or creating new threads?

I looked into the after_filter callback, but it seems like this only lets you execute code before you render the view / response.

Thanks

Does #freeze have a use other than preventing modification?

Ruby's standard uri library has many uses of freeze on components which either can't be modified, or where modification will cause no harm:

  user, password = ui.split(':'.freeze, 2)     # from generic.rb

String#split won't modify its arguments, and even if it did, the code would work properly (Ruby will use a new instance of ':' on the next call).

Here are some more uses of freeze on objects that can't change (these are all from generic.rb)

 if @scheme && @scheme != "ftp".freeze 
 v.delete!("\t\r\n".freeze)
 str << ':'.freeze 

Why are there so many instances of seemingly needless calls to #freeze? Does #freeze have a use beyond preventing modification of its receiver?

Rails Problems with IE

I've got several problems with a Rails 4.2.1 and Ruby 2.1 application in actual IE. If I save something to a database and do a redirect, the values are saved twice in the database.

Does anyone have this as well?

Trying to create log in form with Parse in Rails

so im trying to create a login form for Parse in rails using gem parse-ruby-client and this is what i got so far, i know i have some routing issue i need help with.

heres what i got:

login_controller.rb:

class LoginController < ApplicationController
  def index
    user = Parse::User.authenticate(params[:user][:username],params[:user][:password] )
  end
end

index.html.erb:

<% @page_title = "Log in" %>
<div class="Log_in_Form">
  <h4><center>Log in with your existing "app_name" account</center></h4>
  <%= form_for(:user, :url => {:controller => 'login', :action => 'index'}) do |f| %>
    <center><p> Username:</br> <%= f.text_field :username%> </p></center>
    <center><p> Password:</br> <%= f.password_field :password%></p></center>
    <center><h4><%= f.submit :Login %></h4></center>
  <% end %>
</div>

routes.rb

Rails.application.routes.draw do
  get 'welcome/index'

  root 'login#index'

end

basically i want to be able to input username and password and be directed to the next view being logged in successfully.

Ruby on Rails persistently store Hash from CSV

I have a ruby script written which takes a CSV file and converts the input into a hash:

Culper = File.open('.\CulperCSV.csv')

culper_hash = {}

# set up culper code hash from provided CSV
CSV.foreach(Culper) do |row|
    number, word = row
    culper_hash[word] = number
end

and I am trying to make a Rails app using the script.

My question: How do I store the Hash persistently (or the CSV data so I can build the hash) so that I can minimize load times?

My thoughts:

1) Load the CSV data into a database (seed it) and each time I get a visitor on my site, do the above assignment into a hash but from the db. (not sure how to do this but I can research it).

or

2) Load the complete hash into the database (I think I would have to serialize it?) so that I can do just one fetch from the db and have the hash ready to go.

I am very new to building apps, especially in Rails so please ask questions if what I am trying to do doesn't make sense.

Can I convert an iOS Info.plist into a ruby Hash?

I need to exclude specific keys found in an Info.plist for my app if they are found in another Hash. Currently I can access individual keys in Info.plist like this

setting4Str = `/usr/libexec/PlistBuddy -c \"print :MySettingsDict:setting4" {settings_file}`

and I can get the "setting 4 text" string set at this key in the plist dictionary...

However, I want to be able to iterate over all keys of this MysettingsDict. Does anyone have a method to convert an iOS XML plist to a ruby Dictionary?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://ift.tt/vvUEPL">
<plist version="1.0">
<dict>
    <key>CFBundleDisplayName</key>
    <string>My App</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIdentifier</key>
    <string>com.company.appname</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleLocalizations</key>
    <array>
        <string>en</string>
        <string>de</string>
        <string>it</string>
        <string>fr</string>
        <string>ru</string>
        <string>es</string>
    </array>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>1.3.2</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>com.company.mySchemeName</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>mySchemeName</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>1.3.15.04170</string>
    <key>Internal version</key>
    <string>1.3.15.04170</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>MysettingsDict</key>
    <dict>
        <key>setting1</key>
        <false/>
        <key>setting2</key>
        <false/>
        <key>setting3</key>
        <false/>
        <key>setting4</key>
        <string>setting 4 text</string>
        <key>setting5</key>
        <string>setting 5 text</string>
        <key>setting6</key>
        <false/>
        <key>setting7</key>
        ...

AWS SDK 2.0 Ruby Presigned URL & transcoding the content after upload

My intention:

  1. Get the presigned URL for posting a resource
  2. Post resource to S3 bucket
  3. Transcode my resource on s3 (for video files)

I have figured out 1 & 2 from here after hitting the route, say /getPresignedURL. Has anyone done 3?

My backup plan is to create another route, say /fileUpload which upon successful upload to the presignedURL will return a 200. I will then run a job for transcoding the video, manually. Any easier way to do this? TIA.

how to set proxy to use install gem in cmd

unable to use "gem install rails https://proxy:port already set in environment variables but still

gem install rails  giving error ---- WHile executing gem...(Net::HTTPServeException) 403 "Forbidden"

Ruby on Rails 3: Streaming data and catching exception

I'm streaming data using the following approach:

self.response_body = Enumerator.new do |y|
    10_000_000.times do |i|
        y << "This is line #{i}\n"
    end
end

I'm trying to catch any exception generated inside Enumerator and present something nicer to the user. Right now, the app is presenting an ugly error page from Torquebox. e.g.

Torquebox/Jboss error page.

I tried rescue and redirect_to and many other ways to catch the exception (including add a middleware class for handling exceptions). Any help would be appreciated!.

(The app is made under jruby v1.7.19 and torquebox v3.1.1)

Broken images/css in production mode with Rails 4

I'm running a Rails 4 application in production mode...in Windows 8.1... For some reason y have broken images and css in production mode. Since there is no Passenger gem in Windows, I have to use Apache config to redirect or reverse proxy to Thin:

<VirtualHost *:8888>
    ServerAdmin webmaster@example.com
    ServerName Depot
    #ServerAlias 

    DocumentRoot "c:/my_directory_tree/depot" 

    <Directory "C:/my_directory_tree/depot">
        Require all granted
        Options -MultiViews
    </Directory>

    ProxyPass /depot http://balancerdepot_cluster/
    ProxyPassReverse /depot http://balancerdepot_cluster/
    ProxyPreserveHost On

    <Proxy http://balancerdepot_cluster>
        BalancerMember http://ift.tt/1OTx1pQ
    </Proxy>

    #ErrorLog  "|C:/Webserver/Apache/bin/rotatelogs.exe logs/http://ift.tt/1JBdB8Z 86400" 
    #CustomLog "|C:/Webserver/Apache/bin/rotatelogs.exe logs/http://ift.tt/1OTx1pS 86400" 

combined

</VirtualHost>

And run my application with:

thin -p 3000 -e production --prefix /depot start -p 3001

I already precompiled my assets, but didn't work either.

rake assets:precompile

Why I'm running in production mode my app? Well... before implementing in a real production server, I need to know how to implement this application in Windows server...

Rails 4 form and listing on same page, correct format responses

The goal is to create, edit and destroy model category on index page. I am able to save the model but I can not refresh the listing. I have read many similar examples, its confusing.

This is what I have:

At views/categories/index.html.erb

<!-- Full expand -->
<div class="row mt-20">
        <div class="well-basic">
            <div class="col-xs-8">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Content</th>
                            <th>Actions</th>
                            <th colspan="3"></th>
                        </tr>
                    </thead>

                    <tbody>
                        <% @categories.each do |category| %>
                        <tr>
                            <td><%= category.content %></td>
                            <td> Edit |
                            <%= link_to '', category, method: :delete, data: { confirm: 'Are you sure?' }, class: 'glyphicon glyphicon-remove' %> </td>
                        </tr>
                        <% end %>
                    </tbody>
                </table>

            </div>

            <div class="col-xs-4">
                <%= render '/categories/form', :locals => {:category => @category} %>
            </div>

        </div>
</div>
<!--/ Full expand -->

This is the form at app/categories/_form.html.erb

<%= simple_form_for(@category, remote: true ) do |form| %>
<%= form.error_notification %>

<div class="form-inputs">
    <%= form.input :content %>
</div>

<div class="form-actions">
    <%= form.button :submit, class: 'btn btn-success custom-reload' %>
</div>

<% end %>

Seems like trouble comes here: at app/controllers/categories_controller.rb

class CategoriesController < ApplicationController
def index
    @user = current_user
    @categories = @user.categories
    @category = Category.new 
  end

  def create
    @user = current_user
    @category = @user.categories.build(category_params)

    respond_to do |format|
      if @category.save
        format.html { redirect_to @categories, notice: 'Category has been sucesifully created' }
        format.js {  }
        format.json { render json: @category, status: :created, location: @category }
      else
        format.js { render @categories, notice: 'Category could not been saved.' }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end  
    end

  end

  def destroy
    @category = Category.find(params[:id])
    @category.destroy
    redirect_to :back
  end

  private

  def category_params
    params.require(:category).permit(:content)
  end
end

This is app/views/categories/create.html.erb. First line works, second does not.

$("<%= escape_javascript(render @category") %>).appendTo("#categories")
$('.custom-reload').on('click', function() {    
    window.location.reaload();
});

Please, help, does someone knows how to refresh the page. Even, better, does someone have a full example of this kind of common usage of forms inside listings? (I am still not even trying to edit, but delete works already). Thanks.

Rails instance variables display in development but not on Heroku

I am creating an app with Rails 4.2.3 and Postgres database in development and production, deploying to Heroku. Both my dev and production environment are seeded with the same data.

I have three tables - Cities, Neighborhoods, Venues.

class Venues < ActiveRecord::Base
  belongs_to :neighborhood
end
class Neighborhood < ActiveRecord::Base
  belongs_to :city
  has_many :venues
end
class City < ActiveRecord::Base
  has_many :neighborhoods
end

On the app/views/neighborhoods/show.html.erb page I want to display the Venues that belong to that neighborhood.

The app/controllers/neighborhoods_controller.rb show action is this:

def show
  @city = City.find(params[:city_id])
  @neighborhood = @city.neighborhoods.find(params[:id])
  @venues = Venue.where(neighborhood_id: @neighborhood)
end

The neighborhood routes are embedded in the cities routes, but venues are a separate resource not embedded.

resources :cities do
  resources :neighborhoods
end
resources :venues

The Neighborhood show page for any particular neighborhood displays the neighborhood name, city name, then checks if there are any venues via the @venues instance variable. If so it iterates over each of them, otherwise it states there are no venues. app/views/neighborhoods/show.html.erb

<h1><%= @neighborhood.hood_name + ', ' + @city.city_name %></h1>
<% if @venues.present? %>
  <h3>Venues</h3>
  <% @venues.each do |venue|  %>
    <p><%= link_to venue.venue_name, venue %></p>
  <% end %>        
<% else %>
  <p>There are no venues in this neighborhood</p>
<% end %>

This works fine on my mac in dev mode, but when I load it to Heroku the @venues instance variable is always nil. I confirmed using irb and the console that the venues are indeed in the database on Heroku. They just aren't being recognized. Any idea how to fix this? The logs don't give any clues. From a gem perspective, beside the pg gem, in production I am using gem 'rails_12factor', '0.0.3' and 'puma','~> 2.12.2'.

Additional Information

I tried to just pass a simple instance variable from the controller to the show page for both the cities controller/show page and neighborhood controller/show page. app/controllers/cities_controller.rb

    def show
      @hellocity = "Hello from the show action in the cities controller."
    end

app/controllers/neighborhoods_controller.rb

    def show
      @hellohood = "Hello from the show action in the neighborhoods controller."
    end

Then in the views I called each: app/views/cities/show.html.erb

<%= @hellocity %>

app/views/neighborhoods/show.html.erb

<%= @hellohood %>

The result is in my development environment when I go to any city page I get the hellocity message and when I go to any neighborhood page I get the hellohood message. But when I put this on Heroku I only get the message on the city page. The instance variable is not getting passed to the app/views/neighborhoods/show.html.erb page. @neighborhoods and @cities are being passed but anything else (e.g., @hellohood or @venues) is being blocked. Very strange.

Change scope to use sql

I have two ruby scope but they are not completely using activecord. How can I change it to use only activerecord or sql?

article.rb

class Article < Comfy::Cms::Page
  has_many :view_mappings
  has_many :favorite_mappings
  scope :top_by_number_of_favorites, -> { article.sort_by(&:favorite_score).take(10) }

  scope :top_by_number_of_views, -> { article.sort_by(&:view_score).take(10) }

  def favorite_score
    favorite_mappings.since(2.weeks.ago).count * 5
  end

  def view_score
    view_mappings.since(2.weeks.ago).count
  end

schema.rb

  create_table "view_mappings", force: :cascade do |t|
    t.integer  "article_id"
    t.date     "date_viewed"
    t.string   "device_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "favorite_mappings", force: :cascade do |t|
    t.integer  "article_id"
    t.string   "device_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.date     "date_liked"
  end

HTTParty is escaping JSON

I'm using HTTParty to send data to a remote API, however the API is complaining because the JSON being sent by HTTParty appears to be being escaped, and is thus deemed invalid.

Here's what I'm doing:

query = {"count"=>1,
 "workspaces"=>
  {123445=>
    {"title"=>"Test Project",
     "description"=>"",
     "start_date"=>"2015-06-01T00:00:00.000Z",
     "due_date"=>"2015-08-31T00:00:00.000Z",
     "price_in_cents"=>8000,
     "currency"=>"USD",
     "status_key"=>130,
     "custom_field_values_attributes"=>[],
     "workspace_groups_attributes"=>
      [{"created_at"=>"2015-07-13T11:06:36-07:00",
        "updated_at"=>"2015-07-13T11:06:36-07:00",
        "name"=>"Test Customer",
        "company"=>true,
        "contact_name"=>nil,
        "email"=>nil,
        "phone_number"=>nil,
        "address"=>nil,
        "website"=>nil,
        "notes"=>nil,
        "id"=>"530947",
        "custom_field_values_attributes"=>[]}],
     "id"=>123445}},
 "results"=>[{"key"=>"workspaces", "id"=>123445}]}

Calling to_json on query escapes the JSON too:

"{\"count\":1,\"workspaces\":{\"123445\":{\"title\":\"Test Project\",\"description\":\"\",\"start_date\":\"2015-06-01T00:00:00.000Z\",\"due_date\":\"2015-08-31T00:00:00.000Z\",\"price_in_cents\":8000,\"currency\":\"USD\",\"status_key\":130,\"custom_field_values_attributes\":[],\"workspace_groups_attributes\":[{\"created_at\":\"2015-07-13T11:06:36-07:00\",\"updated_at\":\"2015-07-13T11:06:36-07:00\",\"name\":\"Test Customer\",\"company\":true,\"contact_name\":null,\"email\":null,\"phone_number\":null,\"address\":null,\"website\":null,\"notes\":null,\"id\":\"530947\",\"custom_field_values_attributes\":[]}],\"id\":123445}},\"results\":[{\"key\":\"workspaces\",\"id\":123445}]}"

Is this expected behavior to escape the JSON? Or I'm wondering if the hash I'm building for query is invalid for JSON purposes?

Any help would be greatly appreciated.

iOS NSMutableURLRequest Authorization Header

I am having trouble accessing an API call and I think it has something to do with the authorization header. I am using AlamoFire and printing out the token so I know it is valid.

var URLRequest: NSURLRequest {
    let URL = NSURL(string: Router.baseURLString + path)!
    let mutableURLRequest = NSMutableURLRequest(URL: URL)
    mutableURLRequest.HTTPMethod = method.rawValue

    println(Router.OAuthToken)
    if let token = Router.OAuthToken {
        mutableURLRequest.setValue("Token token=\(token)", forHTTPHeaderField: "Authorization")
    }

    println(mutableURLRequest)

    switch self {
    default:
        return mutableURLRequest
    }
}

This is what the documentation says and it works right in the terminal with the auth token:

curl -H "Authorization: Token token=<ACCESS_TOKEN>" http://ift.tt/1M1QOoI

Here is the error I'm receiving:

Optional(Error Domain=com.alamofire.error Code=-1 "The operation couldn’t be completed. (com.alamofire.error error -1.)")

Regex works on Rubular, but appears to not in RSpec test

I am currently working on these tests. Right now the first 2 will pass but the 3rd one will not.

context "Navigation Functions" do
  let(:nav) {Navigator.new("8801507-001")}
  it "#nav_to_start_folder should navigate to job folder based on stored Work Order number" do
    nav.nav_to_start_folder
    expect(File.basename(Dir.pwd)).to eq("8801507-001 Test Dealer 1 of 4")
  end

  it "#input_csv should return the input CSV when in a folder" do
    expect(nav.input_csv).to eq("test.csv")
  end

  it "#nav_to_next_folder should increment the work order number and job title and create the next folder" do
    nav.nav_to_next_folder
    expect(File.basename(Dir.pwd)).to eq("8801507-002 Test Dealer 2 of 4")
  end
end

The class I am testing is as follows:

class Navigator
def initialize(starting_work_order)
  @workorder = starting_work_order
end

def nav_to_start_folder
  Dir.chdir @workorder[0, 7]
  Dir.chdir Dir.glob("#{@workorder}*").at(0)
end

def input_csv
  arr = Dir.glob('*.csv')
  arr.delete_if { |e| /880\d\d\d\d-\d\d\d ?(for import)?/ =~ e }
  arr.at(0)
end

def nav_to_next_folder
  @title = job_title(File.basename(Dir.pwd))
  Dir.chdir '..'
  next_work_order_number
  next_job_title
  Dir.mkdir @workorder + " " + @title
  Dir.chdir @workorder + " " + @title
end

private

# Info Parser
def next_work_order_number
  @workorder[-3, 3] = next_work_order_seq
end
# Info Parser
def next_work_order_seq
  start_number = @workorder[-3, 3].to_i
  format('%03d', (start_number + 1))
end

# Info Parser
def ipd_style?(folder_name)
  if folder_name[3] == '-'
    false
  else
    true
  end
end

# Info Parser
def job_title(folder_name)
  if ipd_style?(folder_name)
    folder_name[12, (folder_name.length - 11)]
  else
    folder_name[11, (folder_name.length - 10)]
  end
end

# Info Parser
def next_job_title
  /\A(\d*-\d{3}) (?<mainTitle>.+) (?<current>\d+) of (?<total>\d+)\z/ =~ @title
  @title = "#{mainTitle} #{(current.to_i + 1).to_s} of #{total}"
end

end

What appears to be happening is whenever I run next_job_title the regex match groups all come up as nil. I have tested the expression against a few test strings and they all appear to work, but for some reason in this test it won't. Am I missing something subtle (or obvious) about match groups that is causing this to not work?

Also the RSpec failure message is:

 IPDUtils::Navigator Navigation Functions #nav_to_next_folder should increment the work order number and job title and create the next folder
 Failure/Error: expect(File.basename(Dir.pwd)).to eq("8801507-002 Test Dealer 2 of 4")

   expected: "8801507-002 Test Dealer 2 of 4"
        got: "8801507-002  1 of"

My program takes an input from Slack. When an email is provided, Slack automatically converts it to a mail to tag:

<mailto:timxxxx@gmail.com|timxxxx@gmail.com>

I want to easily extract the email IF it is provided in this form, but if the email comes through another channel where it hasn't been reformatted, take the email.

Rails Omniauth missing required parameter: code

Running rails 3.2.18 on c9.io, and I have the gems omniauth and omniauth-google-oauth2 installed. I ran into a problem where I would get a CSRF error on the callback, and it sounded like adding "provider_ignores_state: true" to the params would prevent that, at least for testing and development. It did get rid of the CSRF error, but now there is a new error:

OAuth2::Error

invalid_request: Missing required parameter: code
{
  "error" : "invalid_request",
  "error_description" : "Missing required parameter: code"
}

my config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
    provider :google_oauth2, "clientID", "clientSecret",
    scope: 'profile', image_aspect_ratio: 'square', image_size: 48, access_type: 'online', name: 'google', provider_ignores_state: true
end

Top few lines from the trace:

oauth2 (1.0.0) lib/oauth2/client.rb:113:in `request'
oauth2 (1.0.0) lib/oauth2/client.rb:138:in `get_token'
oauth2 (1.0.0) lib/oauth2/strategy/auth_code.rb:29:in `get_token'
omniauth-oauth2 (1.3.1) lib/omniauth/strategies/oauth2.rb:93:in `build_access_token'
omniauth-google-oauth2 (0.2.6) lib/omniauth/strategies/google_oauth2.rb:77:in `custom_build_access_token'

EDIT: Adding the versions for the gems

/usr/local/rvm/gems/ruby-1.9.3-p547/gems/omniauth-1.2.2
/usr/local/rvm/gems/ruby-1.9.3-p547/gems/omniauth-google-oauth2-0.2.6