dimanche 28 juin 2015

syntax error, unexpected tINTEGER, expecting '('

My code is

 for i in 0..array_dif.count-1
   a = array_dif[i] - array_dif[0]
   b = array_dif[array_dif.count-1] - array_dif[0]
   norm = a.0/b
   array_norm[i] = norm
 end

And i'm getting the following error:

rb:135: no .<digit> floating literal anymore; put 0 before dot (SyntaxError)
    norm = a.0/b
             ^
C:/piegas/config/initializers/backtrace_silencers.rb:135: syntax error, unexpected tINTEGER, expecting '('
    norm = a.0/b
              ^

I don't know whats wrong with it

1;2c OSX mystery: Sometimes 1;2c appears on the next input line

EDIT: Simplified version (skips fuzzing the console for other issues):

pzrq@icebox:~$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> for b in [89,90]: print chr(b)+chr(27)
... 
Y

>> 1;2c

EDIT2: Reproduced in Ruby:

Last login: Mon Jun 29 00:43:22 on ttys000
pzrq@icebox:~$ irb
2.1.1 :001 > for b in [89,90]
2.1.1 :002?>   putc b
2.1.1 :003?>   putc 27
2.1.1 :004?>   end
Y=> [89, 90] 
2.1.1 :005 > 1;2c


Original:

Reproducible (most of the time) enigma I've never seen before:

# Setup
$ mkvirtualenv pycrypto_test
$ pip install pycrypto
$ python

# Script 1
>>> from Crypto import Random
>>> for _ in range(10**3): print(Random.get_random_bytes(130))

# On the next input line, get 1;2c printed 0-10 times
# Just OSX Python 2.7.6, does not affect Homebrew Python 3.4.2
# Happens with or without ipython
>>> 1;2c1;2c1;2c

Have also seen it change the ipython shell prompt twice from normal square brackets (but can't reproduce reliably) to:

In é1ê: 

I'd guess the first script is printing ASCII control characters under Python2, but in Python3 it's just printing byte strings.

# Script 2: Reproduced under (OSX) `brew install python3` v3.4.2 with
>>> for _ in range(10**3):
...   for b in Random.get_random_bytes(130):
...     print(chr(b))

# Lots of output
>>> 1;2c1;2c

What ASCII or other control characters might cause this? Or is there another explanation?

at=error code=H10 desc="App crashed" method=GET path="/" dyno= connect= service= status=503 bytes [on hold]

Thanks for helping! I have been working right with my app in ruby on rails hosted on heroku. Recently i made the last deploy and then in heroku i have this error:

2015-06-23T14:41:26.023607+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=lapapaya.org request_id=6d86d516-71cc-4892-a668-4df4a0326e30 fwd="186.27.168.226" dyno= connect= service= status=503 bytes=

I can't understand what is the origin of the error. It seems it have relation with dyno, but don't understand. Any of you have something similar?

Failure/Error: visit movie_url(movie) ActionView::Template::Error: wrong number of arguments (3 for 0..1)

This question sounds very similar to those that have already been asked and answered thought I can't seem to figure it out.

I have the following error message that makes my spec test fail.

Failures:

  1) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # ./app/views/movies/show.html.erb:24:in `_app_views_movies_show_html_erb__1138068182152565203_70152862507580'
     # ./spec/navigate_movies_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 0.20747 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

Randomized with seed 14064

My actual spec test looks like this:

require 'spec_helper'
include Rails.application.routes.url_helpers

  describe "Navigating movies" do
    it "allows navigation from the detail page to the listing page" do
    ...
    visit movie_url(movie)

    click_link "All Movies"

    expect(current_path).to eq(movies_path)
  end
end

My show page: <%= link_to "All Movies", movies_path %> Edited:

rake routes
Prefix Verb URI Pattern           Controller#Action
movies GET  /movies(.:format)     movies#index
 movie GET  /movies/:id(.:format) movies#show

Edit #3

bundle exec rspec -b
FF.

Failures:

  1) Viewing an individual movie shows the movie's details
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/url_for.rb:150:in `url_for'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:280:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:223:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:345:in `block (2 levels) in define_url_helper'
     # ./app/views/movies/show.html.erb:23:in `_app_views_movies_show_html_erb__342552887677354596_70168586387480'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:145:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:166:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:333:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:143:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:52:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:14:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:42:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:23:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:100:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/streaming.rb:217:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:83:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:32:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/renderers.rb:37:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/rendering.rb:25:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:16:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
     # /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `ms'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:43:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:10:in `default_render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:5:in `send_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:198:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:10:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:20:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:92:in `_run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:776:in `_run_process_action_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:81:in `run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:19:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rescue.rb:29:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:137:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:30:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal.rb:196:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal.rb:237:in `block in action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:74:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:74:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:43:in `serve'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/journey/router.rb:43:in `block in serve'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/journey/router.rb:30:in `each'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/journey/router.rb:30:in `serve'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:819:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/etag.rb:24:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/conditionalget.rb:25:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/head.rb:13:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/params_parser.rb:27:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/flash.rb:260:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/session/abstract/id.rb:225:in `context'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/session/abstract/id.rb:220:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/cookies.rb:560:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/query_cache.rb:36:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/connection_adapters/abstract/connection_pool.rb:649:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:88:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:88:in `_run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:776:in `_run_call_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:81:in `run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/callbacks.rb:27:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/web-console-2.1.3/lib/web_console/middleware.rb:37:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/rack/logger.rb:38:in `call_app'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/rack/logger.rb:20:in `block in call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/tagged_logging.rb:68:in `block in tagged'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/tagged_logging.rb:26:in `tagged'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/tagged_logging.rb:68:in `tagged'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/rack/logger.rb:20:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/request_id.rb:21:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/methodoverride.rb:22:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/runtime.rb:18:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/lock.rb:17:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/middleware/static.rb:113:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/sendfile.rb:113:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/engine.rb:518:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/railties-4.2.1/lib/rails/application.rb:164:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/urlmap.rb:66:in `block in call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/urlmap.rb:50:in `each'
     # /Library/Ruby/Gems/2.0.0/gems/rack-1.6.4/lib/rack/urlmap.rb:50:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rack-test-0.6.3/lib/rack/mock_session.rb:30:in `request'
     # /Library/Ruby/Gems/2.0.0/gems/rack-test-0.6.3/lib/rack/test.rb:244:in `process_request'
     # /Library/Ruby/Gems/2.0.0/gems/rack-test-0.6.3/lib/rack/test.rb:58:in `get'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/browser.rb:59:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/browser.rb:35:in `process_and_follow_redirects'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/browser.rb:21:in `visit'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/rack_test/driver.rb:42:in `visit'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/session.rb:193:in `visit'
     # /Library/Ruby/Gems/2.0.0/gems/capybara-2.1.0/lib/capybara/dsl.rb:51:in `block (2 levels) in <module:DSL>'
     # ./spec/show_movie_spec.rb:9:in `block (2 levels) in <top (required)>'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:114:in `instance_eval'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:114:in `block in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:179:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:179:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/extensions/instance_eval_with_args.rb:16:in `instance_exec'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/extensions/instance_eval_with_args.rb:16:in `instance_eval_with_args'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:247:in `instance_eval_with_args'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:87:in `block (2 levels) in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:89:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:89:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/hooks.rb:418:in `run_hook'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:329:in `run_around_each_hooks'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:256:in `with_around_each_hooks'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:111:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:390:in `block in run_examples'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:386:in `map'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:386:in `run_examples'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:371:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `block (2 levels) in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `map'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `block in run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/reporter.rb:34:in `report'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:25:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'

  2) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie.to_param)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/url_for.rb:150:in `url_for'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:280:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:223:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_dispatch/routing/route_set.rb:345:in `block (2 levels) in define_url_helper'
     # ./app/views/movies/show.html.erb:23:in `_app_views_movies_show_html_erb__342552887677354596_70168586387480'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:145:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:166:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:333:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/template.rb:143:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/abstract_renderer.rb:39:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:53:in `block in render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:52:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/template_renderer.rb:14:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:42:in `render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/renderer/renderer.rb:23:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:100:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/streaming.rb:217:in `_render_template'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:83:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:32:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/renderers.rb:37:in `render_to_body'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/rendering.rb:25:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:16:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `block in ms'
     # /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/benchmark.rb:296:in `realtime'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/core_ext/benchmark.rb:12:in `ms'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:44:in `block in render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:43:in `render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:10:in `default_render'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/implicit_render.rb:5:in `send_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:198:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rendering.rb:10:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:20:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:117:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:555:in `block (2 levels) in compile'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:505:in `call'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:92:in `_run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:776:in `_run_process_action_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/callbacks.rb:81:in `run_callbacks'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/callbacks.rb:19:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/rescue.rb:29:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `block in instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications/instrumenter.rb:20:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/activesupport-4.2.1/lib/active_support/notifications.rb:164:in `instrument'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/instrumentation.rb:30:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/activerecord-4.2.1/lib/active_record/railties/controller_runtime.rb:18:in `process_action'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/abstract_controller/base.rb:137:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionview-4.2.1/lib/action_view/rendering.rb:30:in `process'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-4.2.1/lib/action_controller/metal.rb:196:in `dispatch'
     # /Library/Ruby/Gems/2.0.0/gems/actionpack-
     # /Library/Ruby/Gems/2.0.0/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'

Finished in 0.84651 seconds
3 examples, 2 failures

Failed examples:

rspec ./spec/show_movie_spec.rb:6 # Viewing an individual movie shows the movie's details
rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

rake db:seed -> Mongoid::Errors::NoSessionConfig:

I am building an application in ROR using SQLite.

In the project I include a gem which has run time dependency in Mongoid.

However for my case, I do not use mongoid or any mongodb.

When I am running rake db:seed which I use to fill the fields in my sql database I receive the specific error:

rake aborted!

Mongoid::Errors::NoSessionConfig: Problem: No configuration could be found for a session named 'default'. Summary: When attempting to create the new session, Mongoid could not find a session configuration for the name: 'default'. This is necessary in order to know the host, port, and options needed to connect. Resolution: Double check your mongoid.yml to make sure under the sessions key that a configuration exists for 'default'. If you have set the configuration programatically, ensure that 'default' exists in the configuration hash.

Updating Hash value in Ruby

What i'd like to do is push a bunch of user inputted strings, separated by their spaces to Hash Keys and assign each of those Keys a numerical value from 0 upwards in their order of input. For example;

User input: "a s d f b"

Result:

a => 0
b => 1
c => 2
d => 3
f => 4
b => 5

But my code is only outputting 0 with no increment, please see my code below;

puts "Please enter data:"
text = gets.chomp
words = text.split(" ")
    frequencies = Hash.new(0)

words.each do |k|
    frequencies[k] += 1
end

frequencies.each do |x,y|
    puts x + " " + y.to_s
end

Can anyone see what's wrong with the code above?

Why this won't fetch particular page of the result set?

Following youtube's official API document, I made this code below.
It shows fine if I take off

:pageToken => 5

How can I fetch particular page of the result sets?(I mean pagination here)

Original Code

@search_response = client.execute!(
  :api_method => youtube.search.list,
  :parameters => {
    :part => 'snippet',
    :q => 'cat',
    :maxResults => 10,
    :order => 'date',
    :pageToken => 5
  }
)

Passing parameter to partial view - Rails 4/postgresql/json

I have a Deal model with a column/attribute called 'deal_info' which is a json column.

It looks like this for example

deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" }, 
          { "modal_id": "6", "video2":"yonak" },
          { "modal_id": "9", "video2":"boom" } ] 
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" }, 
          { "modal_id": "11", "video2":"yonak" },
          { "modal_id": "11", "image4":"boom" } ]

On my view deal.html.erb, i have:

<%= for deal_nb in 0..@deal.number_of_deals do %>
  <div class="modal fade" id="myInfoModal<%= modal_nb %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <!-- render the right modal type -->
    <%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: deal_nb  %>
  </div>
<% end %>

Above, as you see above, I'd like to pass for each iteration of the loop inside parameter_i_want_to_pass the number of the iteration loop (2nd iteration would be parameter_i_want_to_pass= 2 for example).

On the partial I have:

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <h4 class="modal-title" id="myModalLabel">this is mt4</h4>
    </div>
    <div class="modal-body">
      this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]['text1'] %> 

    </div>
  </div>

I get the following error:

no implicit conversion of String into Integer (on line "this is the text: <%= @deal.deal_info[parameter_i_want_to_pass]")

Actually I even tried to detect more easily the bug by just passing a set number instead of the variable 'deal_nb'

<%= render "layouts/modal_type_partials/mt#{ @deal.deal_info[deal_nb]['modal_id'] }", parameter_i_want_to_pass: 2  %>

But I still get exactly the same error.

Shoes cannot find its own backend

I just installed Shoes 4, but when I try the most basic program:

require 'shoes'

Shoes.app { button "test" }

It fails with this error:

NameError: uninitialized constant Shoes::Swt::App

I installed shoes using jruby -S gem install shoes --pre, like it says to on github. Why does Shoes.app give me a NameError?

Cancancan ability for specific case

I use cancancan gem for role based authorization rules. I need to preform something like:

can :read, Post, Post.status = 1

This means that user can read post with status = 1. How can i do that?

JSON Parsing in Ruby

I'm trying to parse the below from JSON (using the JSON gem) in Ruby:

"daily":{"summary":"Light rain today through Saturday, with temperatures rising to 88°F on Saturday.","icon":"rain","data":[{"time":1435464000,"precipProbability":0.99}]}

Currently what I have is this: forecast["daily"]["data"], but I want to get the precipProbability for time "1435464000". Any suggestion on how to complete my current JSON parsing "query"?

Is it necessary to use embedded Ruby in Rails?

I'm learning The Ruby on Rails Tutorial and currently going through the sections on embedded Ruby for the html (.html.erb) files. Is it necessary to use embedded Ruby in the html files? Are there major advantages besides code reusability? I'm trying to simply the learning process as much as I can and I'd like to skip the embedded Ruby/html parts if possible.

Cannot use dabatasedotcom objects with Ruby

I'm new to Ruby and I'm trying to connect my application with SalesForce using the database.com gem. My goal is to develop a gem that wraps the Databasedotcom gem, an than use my own wrapper gem in a rails project.

I've installed the databasedotcom gem with bundler.

My Gemfile has the gem declaration:

gem 'databasedotcom'

I've generated my credentials at salesforce (user + pass) and (client_id and client_secret). I used a curl script to test the connection and I was even able to connect to my account.

config/databasedotcom.yml:

host: login.salesforce.com        # Use test.salesforce.com for sandbox
client_secret: mySecret           # This is the Consumer Secret from Salesforce
client_id: myClientID             # This is the Consumer Key from Salesforce
sobject_module: SFDC_Models       # See below for details on using modules
debugging: true                   # Can be useful while developing
username: myusername
password: mypassword

The problem occurs when I'm trying to use the objects inside my code, for example:

require_relative "test_helper"
class SalesforceclientTest < MiniTest::Test
    def test_send_lead
        client = Databasedotcom::Client.new("databasedotcom.yml")
        client.materialize("User")
        @users = Databasedotcom::User.all()[0..19]
    end
end

When I run rake, it gives me the following error:

NameError: uninitialized constant SalesforceclientTest::Databasedotcom

I've also tried to put:

require databasedotcom

in the beginning of the test code, but than, when I re-run rake, it gives me:

require': cannot load such file -- databasedotcom (LoadError)

It's probably something stupid but I can't figure it out. Any help?

Thanks,

Placing a bang before an instance variable - !@my_var

The logged_in? method in the code doesn't use the @ sign to reference the current_user instance variable, does this mean that the variable is local to the logged_in? method or does it still reference the @current_user variable? I noticed if I write !@current_user instead of !current_user the method doesn't work correctly. I am slightly confused how this is working under the hood because would if I had a local variable in logged_in? named current_user and I did not want it to reference the @current_user instance variable above.

def current_user
    @current_user ||= User.find_by(id: session[:user_id])
end

def logged_in?
    !current_user.nil?
end

Pass custom data while subscribing and use it while publishing to a channel - private_pub

I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.

Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.

Following js file is executed when a new message is created.

<% publish_to conversation_messages_path(@conversation.id) do %>
    $("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
    $("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);

The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?

This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.

One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.

ruby on rails install mysql2 but not show

I know may be this is a popular problem but i try many solutions and not get to finish

I try to install mysql in rails with

gem install mysql2

And I get the result

Building native extensions.  This could take a while...
Successfully installed mysql2-0.3.18
1 gem installed

But when i try to execute the command

bundle show mysql2

I get

Could not find gem 'mysql2'.

All these command execute in my application root directory

What is the problem ?

How to display error messages in a multi-model form with transaction?

Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.

The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.

How should I adjust the code below so that also the error messages for user get displayed?

def new
  @organization = Organization.new
  @user = @organization.users.build
end

def create
  @organization = Organization.new(new_params.except(:users_attributes))
  #Validations require the organization to be saved before user, as user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.

  @organization.transaction do
    if @organization.valid?
        @organization.save
        begin
          # Debugger here and then execute next line in debugger responds with: ActiveRecord::Associations::CollectionProxy [#<User id: nil, organization_id: 120, email: "", etc. with all the filled in data.
          @organization.users.create!(users_attributes)
        rescue
          # Should I perhaps add some line here that adds the users errors to the memory?
          raise ActiveRecord::Rollback
        end
     end
  end

  if @organization.persisted?
    flash[:success] = "Yeah!"
    redirect_to root_url
  else
    @user = @organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
    render :new
  end

end

The form view includes:

<%= form_for @organization, url: next_url do |f| %>
    <%= render 'shared/error_messages', object: f.object %>
    <%= f.text_field :name %>
        # Other fields

    <%= f.fields_for :users do |p| %>
        <%= p.email_field :email %>
            # Other fields
    <% end %>

    <%= f.submit "Submit" %>
<% end %>

The error messages partial is as follows:

<% object.errors.full_messages.each do |msg| %>
  <li><%= msg.html_safe %></li>
<% end %>

Update: Following the steps from Rob below I arrived at an errors partial below. This still does not display error messages for User. I added debugger responses inside the code below and for some reason nested_model.errors.any? returns false, while the debugger inside the controller (see above) does return error messages for user.

<% if object.errors.any? %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(object.errors.count, "error") %>.
    </div>

    <ul>
      <% object.errors.full_messages.each do |msg| %>
        <li><%= msg.html_safe %></li>
      <% end %>
    </ul>

  </div>
<% end %>

<% if defined?(nested_models) && nested_models.any? %>
  # Debugger here responds with "local-variable" for "defined?(nested_models)" and for "nested_models.any?" returns true.
  <div id="error_explanation">
    <ul>
      <% nested_models.each do |nested_model| %>
      # Debugger here: "nested_model" still has the values that "nested_models.any?" had, as you would expect. But for "nested_model.errors.any?" it returns false.
        <% if nested_model.errors.any? %>    #Initially had "unless nested_model.valid?" but then errors for User are immediately displayed on loading the form page (new method).
          <ul>
            <% nested_model.errors.full_messages.each do |msg| %>
              <li><%= msg.html_safe %></li>
            <% end %>
          </ul>
        <% end %>
      <% end %>
    </ul>
  </div>
<% end %>

Understanding classes in ruby

I have been doing a lot of reading around Ruby classes and singleton classes. I came across a really interesting article that jolted a question I haven't been able to find a clear answer to yet.

This topic is pretty confusing so hear it goes

If you have a class Dog

class Dog
  def talk
    "bark"
  end
end

This class is the blueprint of any instances of Dog. Ruby stores this blueprint as an object when loading the file/class into memory - e.g. when requiring a file. This object is an instance of the Class class.

Dog.class => Class

So all classes are actually stored as blueprint objects of type Class. The concept of a class is just a means to refer to it with a name, but when dealing with it in Ruby you are actually interacting with objects.

Is this assumption correct?

Give array elements unique IDs

I am trying to multiply every element in an array by the next 12 elements:

array.each do |n|
    a = array.index(n)
    b = a + 12
    product = 1
    array[a..b].each { |i| product *= i }
    highest = product if product > highest
end

I run into a problem when there are multiple occurrences of the same integer in the array:

[1, 2, 3, 7, 5, 4, 7] # this is not the actual array

When the second 7 runs through my block, its array.index(n) becomes 3 (the index of the first 7) when I want it to be 6 (the index of the particular 7 I am working with). I'm pretty sure this can be solved by giving each element of the array a unique 'id', but I'm not sure how I would go about doing this.

My question is, how do I give every element in an array a unique id? The Array#uniq method is not what I am looking for.

Is it possible to use Mechanize library on a Linux web hosting?

I want to use Mechanize library on a Linux host. Then I need Nokogiri and Ruby.

I googled but didn't find my answer:

Is it possible to use Mechanize library on a Linux web hosting?

Undefined method [] in Ruby

I am running Ruby 2.2.2 on Windows 7 Professional. I am trying to make a menu program that stores multiple menus in one array. I thought that I had succeeded, but I get the error message

Menu.rb:7:in 'block in load':undefined method '[]' for nil:NilClass (NoMethodError)

Here is my code:

#-Functions-#
def load(page)
    data = [["menu","Menu",[["obj1","Object 1",false],["exit","Exit",true]]],["obj1","Object 1",[["menu","Back",false],["exit","Exit",true]]],["exit","Exit",false]]
    itemNum = 0
    data.each do
        pageData = data[itemNum]
        if pageData[0] == page
            if pageData[2] == false
                send(page)
            else
                system "cls"
                puts
                puts " #{pageData[1]}"
                puts
                itemNum = 1
                pageData[2].each do
                    puts
                    puts "  #{itemNum}. #{pageData[2][itemNum-1][1]}"
                    itemNum += 1
                end
                puts
                puts
                print " Choice: "
                choice = gets.chomp.to_i
                load(pageData[choice-1][0])
            end
        end
        itemNum +=1
    end
end
def exit
    exit
end

#-Program-#
load("menu")

Ruby: how to parse string '3 days ago'?

Given an input string like 3 days ago, how can I turn it into a date attribute? Maybe something like DateTime.parse('3 days ago')?

ActiveRecord::Base.establish_connection with postgresql on AWS

When got my database.yml configured like this:

default: &default
  adapter: postgresql
  encoding: utf8
  pool: 5
  timeout: 5000

production:
  <<: *default
  host: my_db_address
  port: 5432
  database: my_db_name
  username: my_db_user_name
  password: my_db_password

< test and development ommited >

When I establish connection like this:

ActiveRecord::Base.establish_connection

it says ActiveRecord::AdapterNotSpecified - 'production'

It works hovewer If I do it like this: ActiveRecord::Base.establish_connection( {:adapter => 'postgresql', :database => 'my_db_name', :host => 'my_db_address', :port => '5432', :username => 'my_db_user_name', :password => 'my_db_password'} )

I'd rather load the config from database.yml. How do I do this?

I'm on Rails 4.2.1 and Postgres 9.4

How to share code between ruby refinements?

module Ext
  refine Hash do
    def foo
      puts :in_foo
    end
    def bar
      puts :in_bar
      foo
    end
  end
end
module Test
  using Ext
  Hash.new.bar
end
# in_bar
# in_foo
# => nil

This works as expected. But if I want to share foo and bar between Hash and Array by using include, it fails.

module Shared
  def foo
    puts :in_foo
  end
  def bar
    puts :in_bar
    foo
  end
end
module Ext
  refine Hash do
    include Shared
  end
  refine Array do
    include Shared
  end
end
module Test
  using Ext
  Hash.new.bar
end
# in_bar
# NameError: undefined local variable or method `foo' for {}:Hash

Is there any way to share code between refinements?

Ruby test framework without rails?

I'm working on a few ruby projects that can become web applications with a browser GUI, but for the time being, they are hosted locally and run from the command line. I am not interested in re-structuring the application to use rails.

Most of the code testing solutions out there for ruby seem to be geared toward applications that run rails. Is there a framework in a stable version for testing pure ruby without rails? Where would I find one or any documentation about it?

Undefined Method for `topic_comment_path`

After I make a comment for any particular post and submit the comment via the Create action to add the comment to the database, I get the error Undefined Method for topic_comment_path. From the error, it looks like the route path is not picking up the local variable comment that I am looping through(@post.comments.each do |comment|) in the show.html.erb file? When I refresh the page, and go back and check the post I see the number of comments has increased due to the post being created. But I can't view the comment after I create it on the Posts#show view. Can anyone offer any assistance?

From Show.html.erb file

<% if @post.comments.present? %> 

<h1>Comments</h1>
<% @post.comments.each do |comment| %>
  <div class="media">
    <div class="media-left">
    <%= image_tag(comment.user.avatar.small.url, class: "media-object") if comment.user.avatar? %>
  </div>
<div class="media-body">
    <small>
      <%= comment.user.name %> commented <%= time_ago_in_words(comment.created_at) %> ago
      <% if policy(comment).destroy? %>
        | <%= link_to "Delete", [@topic, @post, comment], method: :delete %>
      <% end %>
    </small>
    <p><%= comment.body %></p>
</div>
  </div>

<% end %>

Screenshot of error in browser

topic_post_comment_path error

Comments table schema

create_table "comments", force: :cascade do |t|
t.text     "body"
t.integer  "post_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer  "user_id"
end

Post controller detail showing the new and create methods for @comment:

class PostsController < ApplicationController


 def show
 @post = Post.find(params[:id])
 @topic = Topic.find(params[:topic_id])

 end

 def new
 @topic = Topic.find(params[:topic_id])
 @post = Post.new
 @comment = Comment.new
 authorize @post 
 authorize @comment 
 end


 def create

 @topic = Topic.find(params[:topic_id])

 @post = current_user.posts.build(post_params)
 @post.topic = @topic
 @comment = Comment.find(params[:id])
 authorize @post 
 authorize @comment

  if @post.save
    flash[:notice] = "Your new post was created and saved."
    redirect_to [@topic, @post] #takes you to the new post you created
  else
    flash[:error] = "There was an error saving the post. Please try again."
    render :new # it grabs the new.html.erb file and pastes it in the view
  end
  end


  def edit
  @topic = Topic.find(params[:topic_id])
  @post = Post.find(params[:id])
  @comment = Comment.find(params[:id])
  authorize @post
  end

Comments Controller

class CommentsController < ApplicationController
 def create
 @topic = Topic.find(params[:topic_id])
 @post = @topic.posts.find(params[:post_id])
 @comment = @post.comments.new(params.require(:comment).permit(:body))
 @comment.user = current_user
 authorize @comment

  @comment.save!#save the code down in the database

 redirect_to [@topic, @post]
 end

def destroy
 @topic = Topic.find(params[:topic_id])
 @post = @topic.posts.find(params[:post_id])
 @comment = @post.comments.find(params[:id])

 authorize @comment
 if @comment.destroy?
  flash[:notice] = "Comment was removed."
  redirect_to [@topic, @post]
 else
  flash[:error] = "Comment couldn't be deleted. Try again."
  redirect_to [@topic, @post]
end
end
end

Rake output

 topic_post_summaries POST        /topics/:topic_id/posts/:post_id/summaries(.:format) summaries#create
                     GET         /topics/:topic_id/posts/:post_id/summaries(.:format) summaries#show
  topic_post_comments POST   /topics/:topic_id/posts/:post_id/comments(.:format)  comments#create
                     DELETE /topics/:topic_id/posts/:post_id/comments(.:format)  comments#destroy
         topic_posts POST   /topics/:topic_id/posts(.:format)                    posts#create
        new_topic_post GET    /topics/:topic_id/posts/new(.:format)                posts#new
        edit_topic_post GET    /topics/:topic_id/posts/:id/edit(.:format)           posts#edit
          topic_post GET    /topics/:topic_id/posts/:id(.:format)                posts#show
                     PATCH  /topics/:topic_id/posts/:id(.:format)                posts#update
                     PUT    /topics/:topic_id/posts/:id(.:format)                posts#update
                     DELETE /topics/:topic_id/posts/:id(.:format)                posts#destroy
              topics GET    /topics(.:format)                                    topics#index
                     POST   /topics(.:format)                                    topics#create
           new_topic GET    /topics/new(.:format)                                topics#new
           edit_topic GET    /topics/:id/edit(.:format)                           topics#edit
               topic GET    /topics/:id(.:format)                                topics#show
                     PATCH  /topics/:id(.:format)                                topics#update
                     PUT    /topics/:id(.:format)                                topics#update
                     DELETE /topics/:id(.:format)                                topics#destroy

rake routes

Rails.application.routes.draw do


get 'comments/create'

devise_for :users

  resources :users, only: [:update] #creates new action users#update
  resources :topics do
  resources :posts, except: [:index] do
  resource :summaries, only: [:create, :show]
  resource :comments, only: [:create, :destroy]
  end

 end

  get 'about' => 'welcome#about'

  root to: 'welcome#index'
  end

how to save class as one of attribute in ROR model

so here is very small help i need for ROR , since i m a newbie in rails community. i m trying to create a model in rails named chat where i have two columns user1 and user2 , i want to store the user object in these. in grails i do this simply as

               class Chat {
                    User user1
                    User user2
                    Date chatStartedOn
                 }

and i m done , i did somewhat same for rails

        rails generate model Chat user1:User user2:User chatStartedOn:date                    

but i run db:migrate it showing me the error

            undefined method `User' for #<ActiveRecord::ConnectionAdapters::TableDefinition

my user migrate file

              class CreateUsers < ActiveRecord::Migration
                def change
                 create_table :users do |t|
                    t.string :username 
                    t.string :email
                    t.string :encrypted_password 
                    t.string :salt
                    t.timestamps
                   end
                end 
                end

Please guide how do i save users object in chat table.. help !

Volt rb framework unable to connect to database

when I fire volt server in the terminal, it gives me this error message

Unable to connect to the database. Volt will still run, but the message bus requires a database connection to setup connections between nodes, so the message bus has been disabled. This means updates will not be propigated between instances (server, console, runners, etc...)

It didn't use to do this before. Even if I delete the repository, generate a new one, fresh, clean, untouched, it still gives me this error. Do I need to install a mongo DB viewer?

Rowspan in prawn-table gives a "Table's width was set too small to contain its contents" error

Admittedly I am still getting the hang of Prawn-table, or even Ruby for that matter. What I am basically trying to do is expand a single cell of a table through the use of colspan and rowspan to hold a sub-table.

While i have got the colspan to work, including rowspan throws up the error specified in the title of this question. What puzzles me is that rowspan should have nothing to do with the width, contrary to what is suggested by the error. Is that not so ?

Any help extended in helping me sort out this error and getting my table format right would be highly appreciated. Thanks in advance for taking some time out to solve this.


Here's the code:

 marks_tb = make_table marks do 
                columns(0).width = 60
                columns(1).width = 210
                columns(2).width = 30
                columns(3).width = 36
                columns(4).width = 36
                columns(5).width = 40
                columns(6).width = 40
                columns(7).width = 35
                columns(8).width = 35
            end 

data = [
        ["","","","Int","Ext","Total", "","",""], 
        [{content: marks_tb,colspan: 9, rowspan: 5}]]

table data, {:position => :center,:cell_style => {border_width: 1,inline_format: true, size: 10, height: 20}}  do
        self.column_widths= {0 => 60,1 => 210,2 => 30,3 => 36, 4 => 36,5 => 40, 6 => 40,7 => 35, 8 => 35}
        row(0).font_style = :bold           
        columns(2..8).align = :center
        #row(3).height = 5
    end

enter image description here

samedi 27 juin 2015

Project Euler 022 'Names scores'

My solution to Project Euler 022 is running incorrectly and I can't see why:

$scores = {
    "A" => 1,
    "B" => 2,
    "C" => 3,
    ...
    "Z" => 26
}

def alphabetScore(name)
    nameScore = 0
    array = name.split(//)
    array.each { |n| nameScore += $scores[n] }
    return nameScore
end

file = File.read("p022_names.txt").split(",")
file.map! { |n| n.tr('^A-Za-z0-9','') }

totalScore = 0

file.each do |findScore|
    nameScore = alphabetScore(findScore)
    totalScore += nameScore
end

p totalScore
# p file # to check that 'file' is indeed an array of strings

Testing individual names e.g p alphabetScore("AGNES") returns the correct value but when totaling the score of every name I get 324536, which is incorrect (the correct answer is 871198282). My only guess as to why this isn't working is that one of the names (presumably the one which would cause totalScore to exceed 324536) is broken in some way.

Ruby Instance Array Is Modified in a Separate Object

Lets say I create an object with an array. I then create another object that takes said array and modifies it within its own scope. If I try to access original array from the first object again, shouldn't I have the unmodified version of the array?

Example code:

class Test
    attr_accessor :g

    def initialize
        @g = [1,2,3]
    end

    def do_stuff
        Test_Two.new(@g).modify
    end

end

class Test_Two
    def initialize(h)
        @h = h
    end

    def modify
        @h[0] +=1
    end

end


t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"

Expected output:

[1,2,3]
[1,2,3]

Actual output:

[1,2,3]
[2,2,3]

Weirdly enough, if I make g an integer, I get what I expect:

class Test
    attr_accessor :g

    def initialize
        @g = 1
    end

    def do_stuff
        Test_Two.new(@g).modify
    end

end

class Test_Two
    def initialize(h)
        @h = h
    end

    def modify
        @h +=1
    end

end


t = Test.new
puts "#{t.g}"
t.do_stuff #this shouldn't modify t.g
puts "#{t.g}"

Output:

1
1

ruby end with a OR operator.

def majority_agreed_commit
  current_commit = log_container.last_commit

  current_term_match_indices = match_indices.values.map do |match_index|
    match_index.downto(current_commit).find do |i|
      log_container.term(i) == current_term
    end || current_commit
  end

I am reading a code piece like this, but I don't understand what's the meaning of this: "end || current_commit" could anybody help me? thanks!

rake aborted! LoadError: cannot load such file

I am completely newbie to this rails frame work and learning via online tutorials. I am in the process of developing a simple application with the help of rails(rails+Mysql).

Currently i am facing an issue with "rake" command.

When i tried to "rake db:schema:dump" the following errors are coming.Pls suggest me some thing.

Thanks in advance.

harsha@Trebuchet:~/simp_cms$ rake db:schema:dump --trace
rake aborted!
LoadError: cannot load such file -- bundler/setup
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/simp_cms/config/boot.rb:3:in `<top (required)>'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/simp_cms/config/application.rb:1:in `<top (required)>'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/harsha/simp_cms/Rakefile:4:in `<top (required)>'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/rake_module.rb:28:in `load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:689:in `raw_load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:94:in `block in load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:93:in `load_rakefile'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:77:in `block in run'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:176:in `standard_exception_handling'
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rake/application.rb:75:in `run'
/home/harsha/.rbenv/versions/2.2.2/bin/rake:33:in `<main>'

harsha@Trebuchet:~/simp_cms$ bundle exec rake db:schema:dump --trace
/var/lib/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/shared_helpers.rb:78: warning: Insecure world writable dir /usr in PATH, mode 040777
Could not find debugger-1.6.8 in any of the sources
Run `bundle install` to install missing gems.

harsha@Trebuchet:~/simp_cms$ gem install debugger -v 1.6.8
Building native extensions.  This could take a while...
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/ext/builder.rb:73: warning: Insecure world writable dir /usr in PATH, mode 040777
ERROR:  Error installing debugger:
    ERROR: Failed to build gem native extension.

    /home/harsha/.rbenv/versions/2.2.2/bin/ruby -r ./siteconf20150628-11403-1nydzd5.rb extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

My Ruby version, rails version and gem list

harsha@Trebuchet:~$ rails -v
Rails 4.2.2
harsha@Trebuchet:~$ rails -v
Rails 4.2.2
harsha@Trebuchet:~$ gem list

*** LOCAL GEMS ***

actionmailer (4.2.2)
actionpack (4.2.2)
actionview (4.2.2)
activejob (4.2.2)
activemodel (4.2.2)
activerecord (4.2.2)
activesupport (4.2.2)
arel (6.0.0)
bigdecimal (1.2.7, 1.2.6)
binding_of_caller (0.7.2)
builder (3.2.2)
columnize (0.9.0)
debug_inspector (0.0.2)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.3.8)
erubis (2.7.0)
globalid (0.3.5)
i18n (0.7.0)
io-console (0.4.3)
json (1.8.3, 1.8.1)
loofah (2.0.2)
mail (2.6.3)
mime-types (2.6.1)
mini_portile (0.6.2)
minitest (5.7.0, 5.4.3)
mysql2 (0.3.18)
nokogiri (1.6.6.2)
power_assert (0.2.3, 0.2.2)
psych (2.0.13, 2.0.8)
rack (1.6.4)
rack-test (0.6.3)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.6)
rails-html-sanitizer (1.0.2)
rake (10.4.2)
rdoc (4.2.0)
spring (1.3.6)
test-unit (3.1.2, 3.0.8)
thread_safe (0.3.5)
tzinfo (1.2.2) 

Please find my database.yml file

  default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  username: simp_cms
  password: secretpassword
  socket: /tmp/mysql.sock

development:
  <<: *default
  database: simp_cms_development

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: simp_cms_test 

please feel free to contact me for any more details...

Update 1: installed bundler and ran "bundle install"

harsha@Trebuchet:~/simp_cms$ gem install bundler
Successfully installed bundler-1.10.5
Parsing documentation for bundler-1.10.5
Done installing documentation for bundler after 5 seconds
1 gem installed
harsha@Trebuchet:~/simp_cms$ gem list

*** LOCAL GEMS ***

actionmailer (4.2.2)
actionpack (4.2.2)
actionview (4.2.2)
activejob (4.2.2)
activemodel (4.2.2)
activerecord (4.2.2)
activesupport (4.2.2)
arel (6.0.0)
bigdecimal (1.2.7, 1.2.6)
binding_of_caller (0.7.2)
builder (3.2.2)
bundler (1.10.5)
columnize (0.9.0)
debug_inspector (0.0.2)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.3.8)
erubis (2.7.0)
globalid (0.3.5)
i18n (0.7.0)
io-console (0.4.3)
json (1.8.3, 1.8.1)
loofah (2.0.2)
mail (2.6.3)
mime-types (2.6.1)
mini_portile (0.6.2)
minitest (5.7.0, 5.4.3)
mysql2 (0.3.18)
nokogiri (1.6.6.2)
power_assert (0.2.3, 0.2.2)
psych (2.0.13, 2.0.8)
rack (1.6.4)
rack-test (0.6.3)
rails-deprecated_sanitizer (1.0.3)
rails-dom-testing (1.0.6)
rails-html-sanitizer (1.0.2)
rake (10.4.2)
rdoc (4.2.0)
spring (1.3.6)
test-unit (3.1.2, 3.0.8)
thread_safe (0.3.5)
tzinfo (1.2.2) 
harsha@Trebuchet:~/simp_cms$ bundle install
Using rake 10.4.2
/var/lib/gems/1.9.1/gems/bundler-1.10.5/lib/bundler.rb:315: warning: Insecure world writable dir /usr in PATH, mode 040777
Using i18n 0.7.0
Using json 1.8.3
Using minitest 5.7.0
Using thread_safe 0.3.5
Using tzinfo 1.2.2
Using activesupport 4.2.2
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile 0.6.2
Using nokogiri 1.6.6.2
Using rails-deprecated_sanitizer 1.0.3
Using rails-dom-testing 1.0.6
Using loofah 2.0.2
Using rails-html-sanitizer 1.0.2
Using actionview 4.2.2
Using rack 1.6.4
Using rack-test 0.6.3
Using actionpack 4.2.2
Using globalid 0.3.5
Using activejob 4.2.2
Using mime-types 2.6.1
Using mail 2.6.3
Using actionmailer 4.2.2
Using activemodel 4.2.2
Using arel 6.0.0
Using activerecord 4.2.2
Using debug_inspector 0.0.2
Using binding_of_caller 0.7.2
Using columnize 0.9.0
Using debugger-linecache 1.2.0
Using debugger-ruby_core_source 1.3.8
Using debugger 1.6.8
Using mysql2 0.3.18
Using bundler 1.10.5
Using thor 0.19.1
Using railties 4.2.2
Using sprockets 3.2.0
Using sprockets-rails 2.3.2
Using rails 4.2.2
Using rdoc 4.2.0
Using sdoc 0.4.1
Using spring 1.3.6
Using web-console 2.1.3
Bundle complete! 6 Gemfile dependencies, 44 gems now installed.
Use `bundle show [gemname]` to see where a bundled gem is installed.
harsha@Trebuchet:~/simp_cms$ 

Now when i tried to use rake command.the below error is coming

harsha@Trebuchet:~/simp_cms$ bundle exec rake
/var/lib/gems/1.9.1/gems/bundler-1.10.5/lib/bundler/shared_helpers.rb:78: warning: Insecure world writable dir /usr in PATH, mode 040777
Could not find debugger-1.6.8 in any of the sources
Run `bundle install` to install missing gems.
harsha@Trebuchet:~/simp_cms$ gem install debugger -v 1.6.8
Building native extensions.  This could take a while...
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/ext/builder.rb:73: warning: Insecure world writable dir /usr in PATH, mode 040777
ERROR:  Error installing debugger:
    ERROR: Failed to build gem native extension.

    /home/harsha/.rbenv/versions/2.2.2/bin/ruby -r ./siteconf20150628-3517-1lyt1uy.rb extconf.rb
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/home/harsha/.rbenv/versions/2.2.2/bin/$(RUBY_BASE_NAME)
/home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:1391:in `initialize': No such file or directory @ rb_sysopen - ./222/ruby_debug.h (Errno::ENOENT)
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:1391:in `open'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:1391:in `copy_file'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:485:in `copy_file'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:402:in `block in cp'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:1570:in `block in fu_each_src_dest'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:1584:in `fu_each_src_dest0'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:1568:in `fu_each_src_dest'
    from /home/harsha/.rbenv/versions/2.2.2/lib/ruby/2.2.0/fileutils.rb:401:in `cp'
    from extconf.rb:83:in `block in <main>'
    from extconf.rb:82:in `each'
    from extconf.rb:82:in `<main>'

extconf failed, exit code 1

Gem files will remain installed in /home/harsha/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/debugger-1.6.8 for inspection.
Results logged to /home/harsha/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/extensions/x86_64-linux/2.2.0-static/debugger-1.6.8/gem_make.out
harsha@Trebuchet:~/simp_cms$  

it seems debugger gem is having some issues but not sure what they are

Ordering ActiveRecord Relation by temporary column field in Rails

I need to order a query of Profile entries in an ActiveRecord::Relation object by a value that is computed on run-time.

I have created and assigned a temporary column distance in my controller for the Relation object by using attr_accessor like so:

@profiles.each do |p|
  p.class_eval do
   attr_accessor :distance
  end
end

@profiles.each do |p|
  p.distance = distance_arr[@profiles.index(p)]  # Distance values obtained from an instance array
end

However, when I try to order the Relation with the order method, I get a no such column: distance error i.e. it's not picking up the temporary field.

Here's how I tried to order it in my controller (note I'm using the will_paginate gem, but that is irrelevant).

@profiles = @profiles.order('distance ASC').paginate(page: params[:page])

Edx Developer Stack error with Vagrant and Ruby

I have a problem in running an instance of edX Platform on my PC. I have followed the intsrunctions which are listed here: http://ift.tt/1qH7XGY I have installed Vagrant 1.7.2 and Oracle VM VirtualBox 4.3.20. However, when I run the command vagrant up I get this error in the command prompt:

[NOTE] You may have encountered a bug in the Ruby interpreter or extension libraries. Bug reports are welcome. For details: This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. I pasted the full log here: http://ift.tt/1BYewia I can't figure a solution. Thanks for any help.

Koala (Rails) for FQL query automatically converting GET request to POST request

I have been using Koala gem for firing FQL queries to fetch facebook data. Normally all FQL queries are GET resquests but I have seen that in facebook's Graph API explorer if the query is too long, its automatically converted to a POST request. Does the Koala gem also exhibits a similar behaviour ?

How do I render multiple lines of HTML in a helper?

I have a helper that looks like this:

if current_user.find_voted_items(vote_scope: :inspired).include?(post)
   link_to vote_inspired_post_path(post, vote_scope: :inspired), method: :post, data: { confirm: 'Are you sure this post Inspires you?' }, class: "btn btn-default" do
    "<i class='fa fa-lightbulb-o'></i> <br />Inspired".html_safe
   end
   link_to vote_happy_post_path(post, vote_scope: :happy), method: :post, data: { confirm: 'Are you sure this post makes you happy?' }, class: "btn btn-success" do
    "<i class='fa fa-smile-o'></i> <br />Happy".html_safe
   end
   link_to vote_disappointed_post_path(post, vote_scope: :disappointed), method: :post, data: { confirm: 'Are you sure this post disappointed you?' }, class: "btn btn-info" do
    "<i class='fa fa-meh-o'></i> <br />Disappointed".html_safe
   end
   link_to vote_upset_post_path(post, vote_scope: :upset), method: :post, data: { confirm: 'Are you sure this post upsets you?' }, class: "btn btn-inverse" do
    "<i class='fa fa-frown-o'></i> <br />Upset".html_safe
   end
end

I need all the links and their nested <i> tags to be rendered - but for some reason, this version is just rendering the last line.

All of that is inside a method called show_vote_buttons(post), that is being called like this in the view: <%= show_vote_buttons(@post) %>

What's the best way to tackle this?

Chef execute fails for the first time

I have a weird problem with a Chef Recipe. Let me tell you that I'm new to Chef so if something looks awfully wrong.

I have my war file, which is built by Spring Boot. I just need to run java -jar <file>.war -config=config/ to run my app.

I recently started experimenting with Chef, and getting to write recipes that do this job.

The code from my recipe is as follows:

#Some code has been omitted intentionally.

directory "#{home}" do
  owner 'root'
  group 'root'
  mode '0755'
  recursive true
end

directory "#{home}/config" do
  owner 'root'
  group 'root'
  mode '0755'
end
cookbook_file "#{home}/config/ehcache.xml" do
  source "ehcache.xml"
  mode "0644"
end
# Get the war file from the repo
remote_file "#{home}/app.war" do
   source "#{node['baseos']['files_repo_url']}/wars/app.war"
   owner 'root'
   group 'root'
   mode '0644'
end

execute 'Run the war file' do
  command "java -jar '#{home}/app.war' -config='#{home}/config/'"
  action :run
end

The war file, and the related config folder along with its contents are successfully being copied to their respective destinations before the execute command gets fired. The problem is when the machine gets freshly created with kitchen create, the first kitchen verify would fail, saying 'Errno::ENOENT: No such file or directory - java -jar /opt/com/app.war -config=config/'. This only happens for the first time. Surprisingly, after saying kitchen verify again, the app starts up, and successfully runs.

This is weird because of the fact that the required file app.war and the config/ are [or should be] already there in the machine with appropriate privileges.

I know Chef processes these things sequentially, so given that the execute command is the very last line in my recipe, it should already have what is required to run the war file. I'm going nuts, can anyone provide some insight into this one?

Thank you!

Ruby Threading Performance: Slow Thread.pass

We're running a threaded ruby server (Puma), and have seen serious performance issues with our Sinatra app. Specifically, something as simple as Thread.pass can take over 2s. How is it possible that a server with 16 threads can take over 2s to return control to a thread? Is the Ruby scheduler that bad, or is there something we can do to fix this?

Details:

  • Ruby implementation: MRI 2.1
  • Sinatra App
  • Running on Heroku 1x dynos
  • Puma server, running 16 threads, 1 process
  • Some routes are doing fairly heavy work, but routes doing almost no work are impacted
  • Over 100MB in free memory

Thanks in advance!

“rails server” on existing application not working

I cloned an application, ran bundle install successfully, then tried running rails server and was met with the following error, which is basically requiring me to scaffold a rails application before using rails commands:

Usage:


 rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]                                      # Path to the Ruby binary of your choice
                                                         # Default: /Users/brianhedberg/.rbenv/versions/2.0.0-p481/bin/ruby
  -m, [--template=TEMPLATE]                              # Path to some application template (can be a filesystem path or URL)
      [--skip-gemfile], [--no-skip-gemfile]              # Don't create a Gemfile
  -B, [--skip-bundle], [--no-skip-bundle]                # Don't run bundle install
  -G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file
      [--skip-keeps], [--no-skip-keeps]                  # Skip source control .keep files
  -O, [--skip-active-record], [--no-skip-active-record]  # Skip Active Record files
  -S, [--skip-sprockets], [--no-skip-sprockets]          # Skip Sprockets files
  -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                         # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]                          # Preconfigure for selected JavaScript library
                                                         # Default: jquery
  -J, [--skip-javascript], [--no-skip-javascript]        # Skip JavaScript files
      [--dev], [--no-dev]                                # Setup the application with Gemfile pointing to your Rails checkout
      [--edge], [--no-edge]                              # Setup the application with Gemfile pointing to Rails repository
  -T, [--skip-test-unit], [--no-skip-test-unit]          # Skip Test::Unit files
      [--rc=RC]                                          # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                            # Skip loading of extra configuration options from .railsrc file

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

    You can specify extra command-line arguments to be used every time
    'rails new' runs in the .railsrc configuration file in your home directory.

    Note that the arguments specified in the .railsrc file don't affect the
    defaults values shown above in this help message.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.

vint-i-vuit in this post: "rails server" on existing working application not starting , but the suggested root of that problem was an issue with Rails 3, and I am on Rails 4.0.5.

Any ideas?

ruby: calling a instance method without using instance

I know in ruby, when we call an instance method, we need to firstly instantiate a class object. But when I see a open sourced code I got confused. The code is like this:

File Message.rb
require 'json'

module Yora
  module Message
    def serialize(msg)
      JSON.generate(msg)
    end

    def deserialize(raw, symbolized_key = true)
      msg = JSON.parse(raw, create_additions: true)
      if symbolized_key
        Hash[msg.map { |k, v| [k.to_sym, v] }]
      else
        msg
      end
    end
  end
end



File. Persistance.rb


require 'fileutils'
require_relative 'message'

module Yora
  module Persistence
    class SimpleFile
      include Message

      def initialize(node_id, node_address)
        @node_id, @node_address = node_id, node_address

        FileUtils.mkdir_p "data/#{node_id}"

        @log_path = "data/#{node_id}/log.txt"
        @metadata_path = "data/#{node_id}/metadata.txt"
        @snapshot_path = "data/#{node_id}/snapshot.txt"
      end

      def read_metadata
        metadata = {
          current_term: 0,
          voted_for: nil,
          cluster: { @node_id => @node_address }
        }
        if File.exist?(@metadata_path)
          metadata = deserialize(File.read(@metadata_path)) #<============
        end

        $stderr.puts "-- metadata = #{metadata}"

        metadata
      end

.....

You can see the line I marked with "<===" It uses deserialize function that been defined in message class. And from message class we can see that method is a instance method, not class method. So why can we call it without instantiating anything like this?

thanks

How to create a Ruby array slice which shares the same instance of the original array?

So that if the slice gets changed, the original array will also change?

a = [1, 2, 3]
b = a[1, 2]
b[0] = 42 # due to COW, only b changes, a remains unchanged

Expected result: when run b[0] = 42, a[1] will also changed to 42.

Raise error on unpermitted parameters rails

I am currently trying to implement raising an error when unpermitted parameters are posted in my RoR back-end. I included

  config.action_controller.action_on_unpermitted_parameters = :raise

in my development.rb configuration. Now, for example I have in one of my controllers:

def apiary_params
    params.require(:apiary).permit(:name, :municipality, :prefecture, :latitude, :longitude, :numberofbeehives, :notes)
end

If I now try posting another parameter lets say "apiary[asdf]" then an internal server error is raised correctly. However if I try posting a random "asdf" param not in the apiary hash, then the request is handled without an error. Does that mean that the random "asdf" and whatever other parameter not in the apiary is permitted? How can I fix that?

Using arrays in regular expressions?

Does anyone know if there is a way to use an array in a regular expression? suppose I want to find out if somefile.txt contains one of an array's elements. Obviously the code below doesn't work, but is there something similar that does work?

array = [thing1 thing2 thing3]
file = File.open("somefile.txt")

file.each_do |line|
if /array/.match(line)
puts line
end

Basically I've got a big list of words to search for, and I'd like to avoid something like this:

($somefile =~ /(thing1|thing2|thing3)/)

How do I test fulltext fields using sunspot_matchers in rspec?

My search controller does this:

search = Sunspot.search(Item) do
  fulltext params[:q] do
    fields(:foo, :bar, :bletch)
  end
end

And in my rspec controller test I have the following:

get :show, :q => q

expect(Sunspot.session).to have_search_params(:fulltext, q, proc do
  fields(:foo, :bar, :bletch)
end)

Side note: when I tried using a block instead of a proc, the block was never executed:

have_search_params(:fulltext, q) do
  # This block was never executed
end

My support/sunspot.rb contains only the following:

Sunspot.session = SunspotMatchers::SunspotSessionSpy.new(Sunspot.session)

When I run the test, I get the following error:

  1) SearchController GET search when a user runs a search performs a fulltext search on the right fields
     Failure/Error: fields(:foo, :bar, :bletch)
     NoMethodError:
       undefined method `fields' for #<Sunspot::DSL::Search:0x007fa0f0da0168>
     # ./spec/controllers/search_controller_spec.rb:28:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/search_controller_spec.rb:27:in `block (4 levels) in <top (required)>'

What's the right way to test that my controller is supplying the correct params when doing a fulltext search? Google yields no relevant results when querying this problem.

How to get stand-alone ohai to recognize custom plugin_path?

I have chef configured to add "/etc/chef/ohai_plugins" to Ohai::Config[:plugin_path]. However, the Chef documentation says:

"The Ohai executable ignores settings in the client.rb file when Ohai is run independently of the chef-client."

So, how can I get a stand-alone run of ohai to load and use the plugins in that custom path?

(Background: I have a custom plugin that reports some information that we keep track of for a fleet of servers, like whether a server has been patched for heartbleed or shellshock. I want to be able to run "ssh somehost ohai", parse the JSON that gets sent back, and extract the information I need.)

Thanks.

Finding smallest prime factor

I am trying to create a function that returns the smallest prime factor of a given number:

require 'prime'

def findSmallestPrimeFactor(number)
  return 2 if number.even?
  return number if Prime.prime? number
  arrayOfFactors = (1..number).collect { |n| n if number % n == 0 }.compact
  arrayOfFactors.each { |n| arrayOfFactors.pop(n) unless Prime.prime? n }
  return arrayOfFactors[0]
end

findSmallestPrimeFactor(13333) returns 1, which should not be happening since 1 should be removed from arrayOfFactors during line 7, as Prime.prime? 1 returns false

It sometimes returns nothing:

puts findSmallestPrimeFactor(13335) # => returns empty line

This issue only occurs when working with a number that is not even and is not prime, i.e lines 4 and 5 are ignored.

Also, when this is finished I will be passing some very large numbers through it. Is there any shorter or more efficient way to do lines 6-8 for larger numbers?

What's the difference between a secure compare and a simple ==(=)

Github's securing webhooks page says:

Using a plain == operator is not advised. A method like secure_compare performs a “constant time” string comparison, which renders it safe from certain timing attacks against regular equality operators.

I use bcrypt.compare('string', 'computed hash') when comparing passwords.

What makes this a "secure compare" and can I do this using the standard crypto library in Node?

Failure/Error: visit movie_url(movie) ActionView::Template::Error: wrong number of arguments (3 for 0..1)

This question sounds very similar to those that have already been asked and answered thought I can't seem to figure it out.

I have the following error message that makes my spec test fail.

Failures:

  1) Navigating movies allows navigation from the detail page to the listing page
     Failure/Error: visit movie_url(movie)
     ActionView::Template::Error:
       wrong number of arguments (3 for 0..1)
     # ./app/views/movies/show.html.erb:24:in `_app_views_movies_show_html_erb__1138068182152565203_70152862507580'
     # ./spec/navigate_movies_spec.rb:12:in `block (2 levels) in <top (required)>'

Finished in 0.20747 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/navigate_movies_spec.rb:5 # Navigating movies allows navigation from the detail page to the listing page

Randomized with seed 14064

My actual spec test looks like this:

require 'spec_helper'
include Rails.application.routes.url_helpers

  describe "Navigating movies" do
    it "allows navigation from the detail page to the listing page" do
    ...
    visit movie_url(movie)

    click_link "All Movies"

    expect(current_path).to eq(movies_path)
  end
end

My show page:

<article>
  <p>
     <%= link_to "All Movies", movies_path %>
  </p>
</article>

Edited:

rake routes
Prefix Verb URI Pattern           Controller#Action
movies GET  /movies(.:format)     movies#index
 movie GET  /movies/:id(.:format) movies#show

Mobile app development using ruby

[I]s there any way to develop android apps using ruby? [I]f any[,] please enlighten me on this,[ ]and please let me know the frameworks used.