Friday, July 8, 2016

How to create a Javascript stubbed object during Rspec feature specs? | Fixed issues

How to create a Javascript stubbed object during Rspec feature specs? | Fixed issues


How to create a Javascript stubbed object during Rspec feature specs?

Posted: 08 Jul 2016 08:42 AM PDT

I have some current feature specs in rspec that currently test some javascript functionality. In those libraries, I am using Modernizr to detect primarily just touchevents. Since I am using Poltergeist and PhantomJS, Modernizr.touchevents always returns true even though I would prefer for it to return false to run other conditionals.

Is there a way to explicitly stub out Modernizr.touchevents or just Modernizr all together?

I have tried the following:

  1. Modernizr.touchevents = false
  2. Modernizr.touchevents = {}
  3. Modernizr = {}
  4. Do not include the modernizr library during tests, however my tests fail because I am expecting Modernizr to be there.

Even if its not Modernizr, how do you stub out javascript libraries especially if you don't care about its functionality at the moment of testing.

Thanks

How to change href in HAML if statement

Posted: 08 Jul 2016 08:53 AM PDT

I have 2 different paths that my workList holds, and they both path to the same place. I want them to path differently. Here's my code:

%table.table-base.table-striped.table-hover{:id => "work-list-table"}    %tbody      - @work_list.each do |workList| //there are two items in this object        %tr{:id => workList.id,href: duplicate_claims_work_lists_path, :style => "cursor:pointer", :onclick=>"workListTrActions(this)"}        -if workList.work_list_name == "Provider Payments"             //href = provider_payments_work_lists_path          %td            %ul.custom-ul              %li                %h4                  =workList.work_list_name  

As you can see, the two items I have both path to duplicate_claims_work_lists_path. I want to change the href to path to provider_payments_work_lists_path. Can I change it in the if statement?

Get index of current version in Rails PaperTrail

Posted: 08 Jul 2016 08:38 AM PDT

I just don't seem to get it straight: How is it possible to receive / determine the index of the current version in some_object.versions using PaperTrail in RoR 4?

best and thanks, Andi

HAML code - need help in changing particular column to editable column ; Ruby on Rails

Posted: 08 Jul 2016 08:29 AM PDT

I want to make the particular 'HC' column to editable column. so that if i make changes in the existing data, the new data should get saved directly into my database. ( Just like double click the particular data the it should goes to editable mode and when i click outside it gets saved or making the entire 'HC' column to editable column and having a common button to save the data.)

Can anyone please help me on this.

Below is my Haml code.

%thead

%tr    %th= sortable_column t("formtastic.labels.organization.city_town"), :column => "City/town"    - if view_zone      %th= sortable_column t("formtastic.labels.organization.Zone"), :column => "Zone"    %th.number= sortable_column t("formtastic.labels.organization.HC"), :column => "HC", :direction => :desc    %th.number= sortable_column t("formtastic.labels.organization.%_of_HC"), :column => "%_of_HC", :direction => :desc    %th.number= sortable_column t("formtastic.labels.organization.Overall_%"), :column => "Overall_%", :direction => :desc    - if current_user.admin?      %th   

%tbody

    %td= organization.city/town      - if view_zone        %td          - if organization.zone            = organization.zone.abbr      %td.number= number_with_delimiter zeroblank(organization.HC)      %td.number= number_to_percentage((organization.%_of_HC || 0) * 100, :precision => Settings.user_count_percentage_precision || 2)      %td.number= over_under(organization.Overall_%, organization.%_of_HC, :format => [:image, :actual])  

Click here to check how the page actually looks like now

Is there a Gem to preprocess ruby code and find errors that would occur runtime?

Posted: 08 Jul 2016 08:49 AM PDT

We have huge code base and we are generating issues that would have been caught at compile time in type languages such as Java but we are not catching them until runtime in Ruby. This is bad since we generate bugs that most of the time are typos or refactoring that leaves some invalid code.

Example:

def mysuperfunc      # some code goes here        # this was a valid call but not anymore since enforcesecurity      # signature changed      @system.enforcesecurity  end  

I mean, IDEs can do it but some guys use ATOM or sublime, so we need something to "compile" and report that kind of issues so they don't reach deployment. What have you been using?

This is generating a little percentage of our bug reports, but since we are forced to produce at a ridiculous pace we don't have 100% code coverage. If there is no tool to help, I'll just make sure everybody uses and IDE and run the reports with tools such as Rubymine.

Our stack includes, rspec, minitest, SimpleCov. We enforce code reviews, multistack deployments (dev, qa, pre-prod, sandbox, prod). And still some issues are reaching higher level and makes us programmers look bad. I'm not looking of magic, just a little automation that might help a bit.

Capistrano error while deploy (command not found: sneakersctl)

Posted: 08 Jul 2016 08:14 AM PDT

I'm getting the following error while deploy, that can't find out what's going on.

Any ideas?

The deploy has failed with an error: #<SSHKit::Runner::ExecuteError:  Exception while executing as deploy@###.###.##.##: bundle exit status: 127  bundle stdout: Warning: the running version of Bundler is older than the version that created the lockfile.  We suggest you upgrade to the latest version of Bundler by running `gem install bundler`.  bundler: command not found: sneakersctl  

Cannot bundle install after cloning

Posted: 08 Jul 2016 08:30 AM PDT

I've been having problems running bundle install on my console every time I clone a project. But I face no problems running bundle install if I make my own project.

Anyone know what's up?

Fetching gem metadata from http://rubygems.org/  Fetching version metadata from http://rubygems.org/  Fetching dependency metadata from http://rubygems.org/  Resolving dependencies....  Using rake 11.2.2  Using i18n 0.7.0  Using json 1.8.3  Using minitest 5.9.0  Using thread_safe 0.3.5  Using builder 3.2.2  Using erubis 2.7.0  Using mini_portile2 2.1.0  Using pkg-config 1.1.7  Using rack 1.6.4  Using mime-types-data 3.2016.0521  Using arel 6.0.3  Using coderay 1.1.1  Using debug_inspector 0.0.2  Using bundler 1.12.5  Using coffee-script-source 1.10.0  Using execjs 2.7.0  Using thor 0.19.1  Using concurrent-ruby 1.0.2  Using multi_json 1.12.1  Using sass 3.4.22  Using tilt 2.0.5  Using spring 1.7.2  Installing sqlite3 1.3.11 with native extensions    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /Applications/rubystack-2.2.5-3/ruby/bin/ruby -r ./siteconf20160708-85177-1q2ntd0.rb extconf.rb  checking for sqlite3.h... *** 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=/Applications/rubystack-2.2.5-3/ruby/bin/$(RUBY_BASE_NAME)      --with-sqlite3-dir      --without-sqlite3-dir      --with-sqlite3-include      --without-sqlite3-include=${sqlite3-dir}/include      --with-sqlite3-lib      --without-sqlite3-lib=${sqlite3-dir}/lib  /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)  You have to install development tools first.      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:587:in `try_cpp'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:1113:in `block in find_header'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:911:in `block in checking_for'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:351:in `block (2 levels) in postpone'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:321:in `open'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:351:in `block in postpone'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:321:in `open'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:347:in `postpone'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:910:in `checking_for'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:1112:in `find_header'      from extconf.rb:30:in `<main>'    extconf failed, exit code 1    Gem files will remain installed in /Applications/rubystack-2.2.5-3/ruby/lib/ruby/gems/2.2.0/gems/sqlite3-1.3.11 for inspection.  Results logged to /Applications/rubystack-2.2.5-3/ruby/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-10/2.2.0-static/sqlite3-1.3.11/gem_make.out  Using turbolinks-source 5.0.0  Using rdoc 4.2.2  Using tzinfo 1.2.2  Installing nokogiri 1.6.8 with native extensions    Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /Applications/rubystack-2.2.5-3/ruby/bin/ruby -r ./siteconf20160708-85177-1kbeqyk.rb extconf.rb --with-opt-dir=/usr   Using pkg-config version 1.1.7  checking if the C compiler accepts -I/Applications/rubystack-2.2.5-3/common/include/ImageMagick -I/Applications/rubystack-2.2.5-3/common/include -I/Applications/rubystack-2.2.5-3/common/include/ImageMagick -I/Applications/rubystack-2.2.5-3/common/include  -I/Applications/rubystack-2.2.5-3/sqlite/include -I/Applications/rubystack-2.2.5-3/varnish/include -I/Applications/rubystack-2.2.5-3/python/include -I/Applications/rubystack-2.2.5-3/mysql/include -I/Applications/rubystack-2.2.5-3/postgresql/include -I/Applications/rubystack-2.2.5-3/apache2/include -I/Applications/rubystack-2.2.5-3/subversion/include -I/Applications/rubystack-2.2.5-3/common/include -I/usr/include -m64... *** 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      --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=/Applications/rubystack-2.2.5-3/ruby/bin/$(RUBY_BASE_NAME)      --help      --clean  /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)  You have to install development tools first.      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:571:in `block in try_compile'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:522:in `with_werror'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:571:in `try_compile'      from extconf.rb:138:in `nokogiri_try_compile'      from extconf.rb:162:in `block in add_cflags'      from /Applications/rubystack-2.2.5-3/ruby/lib/ruby/2.2.0/mkmf.rb:619:in `with_cflags'      from extconf.rb:161:in `add_cflags'      from extconf.rb:414:in `<main>'    extconf failed, exit code 1    Gem files will remain installed in /Applications/rubystack-2.2.5-3/ruby/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.8 for inspection.  Results logged to /Applications/rubystack-2.2.5-3/ruby/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-10/2.2.0-static/nokogiri-1.6.8/gem_make.out  Using rack-test 0.6.3  Using mime-types 3.1  Using better_errors 2.1.1  Using binding_of_caller 0.7.2  Using coffee-script 2.4.1  Using uglifier 3.0.0  Using sprockets 3.6.3  An error occurred while installing sqlite3 (1.3.11), and Bundler cannot  continue.  Make sure that `gem install sqlite3 -v '1.3.11'` succeeds before bundling.  

I'm trying to run a ruby project file uploaded on github, and I was able to successfully clone it and I know I'm supposed to install the gems before I'm able to execute rails s but every time I try to run bundle install it gives me this really long line of code^

However, whenever I make a project of my own using rails new ___ I'm able to execute bundle install properly, install the gems and execute rails s I don't understand why it isn't working for when I clone another project.

Send f.select parameter to jquery and show dynamic form elements

Posted: 08 Jul 2016 07:58 AM PDT

I have a form who uses a nasted form. I want to him show up when the f.select selects the option unificação.

I using a example that i see in a example, when i select a new option the alert appers, but i don't know how i send the selected element to function and how i tell to him to show the f.fields_for :unifications.

<div class="form-row">      <label>          <span>Evento</span>              <%= f.select :event, ['Reencaminhar', 'Reclassificar', 'Rejeitar alteracão de diagnóstico', 'Rejeitar reencaminhamento', 'Solicitar esclarecimento', 'Cancelar solicitação', 'Rejeitar cancelamento', 'Responder', 'Unificação', 'Envio de cópia de ID', 'Reiterar', 'Registrar Solicitação', 'Reabrir solicitação', 'Complementar solicitação'], {}, :onChange => "fillForm.test(this)" %>      </label>          </div>    <%= f.fields_for :unifications do |unification_form| %>      <label>          <%= unification_form.link_to_remove "Remover cpf" %>          <%= unification_form.text_field :cpf %>            </label>  <% end %>    requests.coffee     @fillForm =      test: ->          alert('Hello world')  

Can someone help-me with this situation? I'm new in rails and in web development.

Thanks.

switched from rbenv from rvm and now not able to rails s. can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)

Posted: 08 Jul 2016 07:57 AM PDT

FIRST ERROR:

`check_version_conflict': can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)  

TURNED INTO THIS ERROR:

/Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `require': dlopen(/Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.bundle, 9): Library not loaded: /Users/phillipjones/.rvm/rubies/ruby-2.3.1/lib/libruby.2.3.0.dylib (LoadError)    Referenced from: /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.bundle    Reason: image not found - /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.bundle  

These are the the circumstances leading up to this issue and my steps to try and resolve:

After switching to rbenv from rvm I am having trouble with apps that I created using rvm. I cannot run rails s.

First I got this error:

Phillip-Joness-MacBook:messengerApp phillipjones$ rails s  /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:2274:in `check_version_conflict': can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:1403:in `activate'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:68:in `block in gem'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `synchronize'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `gem'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/postit_trampoline.rb:32:in `<top (required)>'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/setup.rb:2:in `<top (required)>'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/workspace/messengerApp/config/boot.rb:3:in `<top (required)>'      from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `require_relative'      from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `<top (required)>'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `load'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client/rails.rb:28:in `call'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client/command.rb:7:in `call'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/client.rb:30:in `run'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/bin/spring:49:in `<top (required)>'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `load'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.1/lib/spring/binstub.rb:11:in `<top (required)>'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/workspace/messengerApp/bin/spring:13:in `<top (required)>'      from bin/rails:3:in `load'      from bin/rails:3:in `<main>'  

Then I tried bundle update. no change so I tried to install the bundler gem:

Phillip-Joness-MacBook:messengerApp phillipjones$ gem install bundler  Successfully installed bundler-1.12.5  Parsing documentation for bundler-1.12.5  Done installing documentation for bundler after 5 seconds  1 gem installed  

no change.

I tried to install the exact bundler version

Phillip-Joness-MacBook:messengerApp phillipjones$ gem install bundler-1.12.5  ERROR:  Could not find a valid gem 'bundler-1.12.5' (>= 0) in any repository  

no change.

I homebrew installed rbenv-bundler

hillip-Joness-MacBook:rubygems phillipjones$ brew install rbenv-bundler  ==> Downloading https://github.com/carsomyr/rbenv-bundler/archive/0.99.tar.gz  ==> Downloading from https://codeload.github.com/carsomyr/rbenv-bundler/tar.gz/0.99  ######################################################################## 100.0%  🍺  /usr/local/Cellar/rbenv-bundler/0.99: 13 files, 46.6K, built in 10 seconds  

installed the bundler again, deleted the gemlock.file and ran a bundle install

Phillip-Joness-MacBook:rubygems phillipjones$ gem install bundler  Successfully installed bundler-1.12.5  Parsing documentation for bundler-1.12.5  Done installing documentation for bundler after 5 seconds  1 gem installed  Phillip-Joness-MacBook:rubygems phillipjones$ bundle install  Could not locate Gemfile  Phillip-Joness-MacBook:rubygems phillipjones$ cd ~/workspace/messengerApp/  Phillip-Joness-MacBook:messengerApp phillipjones$ bundle install  Using rake 11.2.2  Using i18n 0.7.0  Using json 1.8.3  Using minitest 5.9.0  Using thread_safe 0.3.5  Using builder 3.2.2  Using erubis 2.7.0  Using mini_portile2 2.1.0  Using pkg-config 1.1.7  Using rack 1.6.4  Using mime-types-data 3.2016.0521  Using arel 6.0.3  Using ansi 1.5.0  Using execjs 2.7.0  Using debug_inspector 0.0.2  Using thor 0.19.1  Using sass 3.4.22  Using byebug 9.0.5  Using coderay 1.1.1  Using coffee-script-source 1.10.0  Using concurrent-ruby 1.0.2  Using ffi 1.9.13  Using bundler 1.12.5  Using formatador 0.2.5  Using rb-fsevent 0.9.7  Using ruby_dep 1.3.1  Using lumberjack 1.0.10  Using nenv 0.3.0  Using shellany 0.0.1  Using method_source 0.8.2  Using slop 3.6.0  Using guard-compat 1.2.1  Using multi_json 1.12.1  Using turbolinks-source 5.0.0  Using ruby-progressbar 1.8.1  Using tilt 2.0.5  Using spring 1.7.2  Using sqlite3 1.3.11  Using rdoc 4.2.2  Using tzinfo 1.2.2  Using nokogiri 1.6.8  Using rack-test 0.6.3  Using mime-types 3.1  Using autoprefixer-rails 6.3.7  Using uglifier 3.0.0  Using binding_of_caller 0.7.2  Using bootstrap-sass 3.2.0.2  Using coffee-script 2.4.1  Using sprockets 3.6.3  Using rb-inotify 0.9.7  Using notiffany 0.1.0  Using pry 0.10.3  Using guard-minitest 2.4.4  Using turbolinks 5.0.0  Using minitest-reporters 1.1.9  Using sdoc 0.4.1  Using activesupport 4.2.6  Using loofah 2.0.3  Using mail 2.6.4  Using listen 3.1.5  Using rails-deprecated_sanitizer 1.0.3  Using globalid 0.3.6  Using activemodel 4.2.6  Using jbuilder 2.5.0  Using rails-html-sanitizer 1.0.3  Using guard 2.13.0  Using rails-dom-testing 1.0.7  Using activejob 4.2.6  Using activerecord 4.2.6  Using actionview 4.2.6  Using actionpack 4.2.6  Using actionmailer 4.2.6  Using railties 4.2.6  Using sprockets-rails 3.1.1  Using simple_form 3.2.1  Using bootstrap-datepicker-rails 1.6.1.1  Using bootstrap-modal-rails 2.2.5  Using coffee-rails 4.1.1  Using font-awesome-rails 4.6.3.1  Using jquery-rails 4.1.1  Using jquery-turbolinks 2.1.0  Using responders 2.2.0  Using rails 4.2.6  Using sass-rails 5.0.5  Using web-console 2.3.0  Using figaro 0.7.0  Using rails-controller-testing 0.0.3  Bundle complete! 28 Gemfile dependencies, 87 gems now installed.  Gems in the group production were not installed.  Bundled gems are installed into ./vendor/bundle.  

then I checked the rbenv local. did a rbenv rehash. checked the rake. and tried rails s again. this time I got a new error:

Phillip-Joness-MacBook:messengerApp phillipjones$ rbenv local  ruby-2.3.1  Phillip-Joness-MacBook:messengerApp phillipjones$ rbenv rehash  Phillip-Joness-MacBook:messengerApp phillipjones$ rbenv which rake  /Users/phillipjones/.rbenv/versions/2.3.1/bin/rake  Phillip-Joness-MacBook:messengerApp phillipjones$ rails ss  /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:2274:in `check_version_conflict': can't activate bundler-1.12.5, already activated bundler-1.13.0.rc.1 (Gem::LoadError)      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:1403:in `activate'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:68:in `block in gem'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `synchronize'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:67:in `gem'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/postit_trampoline.rb:32:in `<top (required)>'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/bundler-1.13.0.rc.1/lib/bundler/setup.rb:2:in `<top (required)>'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/workspace/messengerApp/config/boot.rb:3:in `<top (required)>'      from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `require_relative'      from /Users/phillipjones/workspace/messengerApp/bin/rails:8:in `<top (required)>'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'      from /Users/phillipjones/workspace/messengerApp/vendor/bundle/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /Users/phillipjones/workspace/messengerApp/bin/spring:13:in `<top (required)>'      from bin/rails:3:in `load'      from bin/rails:3:in `<main>'  

Multiple selection in edit form shows more than one time

Posted: 08 Jul 2016 07:54 AM PDT

I have a form that has nested attributes.

The form is about products and a product has many locations. I am trying to list the locations in a dropdown manner using collection_select but it shows more than one time (twice in fact). What am I doing wrong?

Relevant part of the form:

<%= f.fields_for :stocks do |ff| %>      <div class="input-field  margin-top x-4">        <%= collection_select :product, :location_ids, Location.all, :id, :structured_location , {:prompt => "Please Select Locations for Product"}, {multiple: true} %>        <%= f.label :locations %>      </div>     <% end %>  

Unequally interleave two ruby arrays

Posted: 08 Jul 2016 08:40 AM PDT

I'd like to interleave two arrays without exactly alternating them. For example, given:

a = [1,2,3,4,5,6,7,8,9]  b = ['a','b','c']  

I'd like to receive f = [1,2,'a',3,4,'b',5,6,'c',7,8,9] as the output. I want one element from b for every two elements in a.

A solution appears to be:

a = [1,2,3,4,5,6,7,8,9]  b = ['a','b','c']    even, odd = a.partition.each_with_index{ |_, i| i.even? }  res = even.zip(odd,b)  res = res.flatten.reject(&:blank?)  #=> [1, 2, "a", 3, 4, "b", 5, 6, "c", 7, 8, 9]  

but I'm not thrilled with this solution. Any ideas?

Couldn't hit the javascript files in Rails

Posted: 08 Jul 2016 07:44 AM PDT

I can't able to hit the javascript when I click on the button. Previously the application is in Rails 3.2 and now I migrated to 4.2.6. I didn't change any js related ones. Please help. This is my code in short:

app/views/reports/_creation.html.erb:

<div id="instagram-inline-js">    <%= render :partial => "photos_inline_js" %>  </div>  <a class="purple_button _round_5" id="select-files-upload-button">Select file(s)</a>  

app/views/reports/_photos_inline_js.html.erb:

<script type="text/javascript">      $('#select-files-upload-button').live("click", function() {        $('#select-photos').show();      });  </script>  

Error message when installing new rails app ( error when installing byebug)

Posted: 08 Jul 2016 07:40 AM PDT

When launching a new rails app with the command "rails new movie_reviews", I get the following error message in my console:

"An error occurred while installing byebug (9.0.5), and Bundler cannot continue. Make sure that gem install byebug -v '9.0.5' succeeds before bundling."

This makes it impossible to install RUbygems such as "Devise" and others.

Do you know how to revolve the problem?

Encoding::UndefinedConversionError: U+20AC from UTF-8 to ISO-8859-1

Posted: 08 Jul 2016 07:22 AM PDT

In console:

"Développement".encode("iso-8859-1").force_encoding("utf-8")    str= "capital buffers for ccps ‘the way forward’, says cpmi chair"    str.encoding.name #"UTF-8"    str.encode("iso-8859-1").force_encoding("utf-8")    

#Encoding::UndefinedConversionError: U+20AC from UTF-8 to ISO-8859-1

I want to convert str to Readable String.

Transform curl to open-uri in ruby?

Posted: 08 Jul 2016 07:05 AM PDT

I have a curl line like this:

curl https://api.paymill.com/v2.1/checksums -u 'private_user_key' -d 'checksum_type=paypal' -d 'amount=4200'  

and I want to transform it into a open-uri call like this:

require 'open-uri'  open("https://api.paymill.com/v2.1/checksums", http_basic_authentication: ['private_user_key'])  

Works so far, but how do I include the -d data-attributes like -d 'checksum_type=paypal' -d 'amount=4200'?

Thanks, Andreas

Passing in %20 as part of url to Twitter web intents but it shows as ' ' blank space

Posted: 08 Jul 2016 07:06 AM PDT

My valid url is website.com/my%20name when I pass this into Twitter web intents the %20 gets extracted to a blank space... but this creates a bad url.

Any ideas how I can get this url in?

Fetch ActiveRecord query result as an array of hashes with chosen attributes

Posted: 08 Jul 2016 08:48 AM PDT

The model User has first, last and login as attributes. It also has a method called name that joins first and last.

What I want is to iterate through the Users records and create an array of hashes with the attributes I want. Like so:

results = []  User.all.map do |user|      record = {}      record["login"] = user.login      record["name"] = user.name      results << record  end  

Is there a cleaner way in Ruby to do this?

Redcarpet Custom Markdown Parser class. How to render partial in Helper class as a response

Posted: 08 Jul 2016 06:47 AM PDT

I created a custom markdown parser class for Redcarpet because there is some custom syntax I want to parse on my blog. I want the image parser to return a whole HTML structure. It would be tedious to maintain this html (say 20 lines of divs with classes and static text) inside a Ruby string, which is why I tried to extract this into a partial.

The image method below parses the markdown syntax and then passes the title, image link and html classes to the partial.

My question is how I can make this work. I've tried render which doesn't render to the response body and render_to_string which doesn't work either as the returned string seems to be nil.

If there is another way to extract HTML/ERB code from my ruby code then let me know. I really don't want to hack HTML code inside a string variable.

CustomerMarkdownParser class inside application_helper.rb

class CustomMarkdownParser < Redcarpet::Render::HTML      include ActionView::Helpers::UrlHelper          include ActionView::Helpers::AssetTagHelper          include AbstractController::Rendering              def parse_media_link(link)              # parsing code          end            # ![This is an image](imageurl)          # ![Image referenced by slug](theslug)          # ![Image referenced by slug and version](theslug|post)          # ![Image referenced by slug, version and with classes](theslug||center)          def image(link, title, alt_text)              size = nil              klass = nil                if nil != (parse = parse_media_link(link))                  puts parse                  image = Image.find_by_id(parse[:id]) || Image.find_by_slug(parse[:id])                  caption_text = ""                  link = ""                  if image                      klass = parse[:class]                      if klass.match(/right|left/) # use smaller image version for left/right floating images                          link = image.file_url(:small)                      else                          link = image.file_url(:post)                      end                      caption_text = parse[:alt_text]                      image.caption ||= parse[:alt_text]                      image.save                    end              end              # I have a partial called post_image that contains               #the image HTML code I want this method to return.              render_to_string 'application/post_image', locals: {url: link, caption: caption_text, class: klass}    end  

EDIT 1: I have heard of the render_anywhere gem, but it seems really dodgy to add a whole gem just to achieve this simple task.

Rails 3 validate uniqueness with conditions [duplicate]

Posted: 08 Jul 2016 06:44 AM PDT

This question already has an answer here:

i have a model with name, longitude and latitude columns. I want to validate the uniqueness of all newly added records against name, but if the latitude or longitude is different then we can have a records with same name.

(Sorry for my bad english :D)

Example:

place1 = Place.create(name: 'Pizza', latitude: 11.12345, longitude: 11.12345)  place2 = Place.create(name: 'Pizza', latitude: 11.12345, longitude: 11.12345)  place3 = Place.create(name: 'Pizza', latitude: 15.54321, longitude: 11.12345)    place1.valid? => true  place2.valid? => false  place1.valid? => true  

NameError in Devise::SessionsController#create undefined local variable or method `controller_path' for #<Devise::SessionsController

Posted: 08 Jul 2016 06:47 AM PDT

I'm working on a rails app that had basic user auth functionality via devise gem. Sign in was working fine, but I realized now that I sign up it throws me the following error:

ActionController::UrlGenerationError in Devise::SessionsController#create  No route matches {:action=>"show", :controller=>"controllers"} missing required keys: [:id]  

I didn't create a controller named Controllers, and the error refers to Devise, so I figured something is wrong with the way I'm passing user details into the Devise controller/ with the way I'm handling routes. So I looked into my config/routes.rb and I saw the following line:

  resources :controllers  

I have no recollection of adding this line. It's possible that I was debugging something a while ago and threw this line in there but from what I saw in the devise wiki nothing like this should have been auto-generated. So when I deleted that line, signing in then threw the following error:

NameError in Devise::SessionsController#create  undefined local variable or method `controller_path' for #<Devise::SessionsController:0x007fe6b6cd6730> Did you mean? controller_name  

Here is my Controller controller:

class ControllersController < ApplicationController    before_action :set_controller, only: [:show, :edit, :update, :destroy]      # GET /controllers    # GET /controllers.json    def index      @controllers = Controller.all    end      # GET /controllers/1    # GET /controllers/1.json    def show    end      # GET /controllers/new    def new      @controller = Controller.new    end      # GET /controllers/1/edit    def edit    end      # POST /controllers    # POST /controllers.json    def create      @controller = Controller.new(controller_params)        respond_to do |format|        if @controller.save          format.html { redirect_to @controller, notice: 'Controller was successfully created.' }          format.json { render :show, status: :created, location: @controller }        else          format.html { render :new }          format.json { render json: @controller.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /controllers/1    # PATCH/PUT /controllers/1.json    def update      respond_to do |format|        if @controller.update(controller_params)          format.html { redirect_to @controller, notice: 'Controller was successfully updated.' }          format.json { render :show, status: :ok, location: @controller }        else          format.html { render :edit }          format.json { render json: @controller.errors, status: :unprocessable_entity }        end      end    end      # DELETE /controllers/1    # DELETE /controllers/1.json    def destroy      @controller.destroy      respond_to do |format|        format.html { redirect_to controllers_url, notice: 'Controller was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_controller        @controller = Controller.find(params[:id])      end    end  

I haven't overridden Devise's Controller method at all, but it seems that Devise requires resources :controller? I'm not sure I fully understand the problem here. But does anyone know what I can do to fix this?

Practical usage of Hadoop in project

Posted: 08 Jul 2016 06:23 AM PDT

I'm going to use Hadoop in my new project. The project concept is like on the following image: enter image description here

User has device which produces some data (logs). User can get data from device as a file and upload it to web app/hadoop. I'm going to build web app using Ruby on Rails.

I know some basics of Hadoop (HDFS, Mappers, Reducers), but I don't know how to use Hadoop in practical way. The project is now only a concept, because I would like to get some tips first and then adjust project's components to collected tips.

My major considerations are about:

  1. Web app should be stored on the same location as Hadoop? (the same server/cloud/service provider)
  2. How to upload files? Can be in the web app form to upload files? Or is it better to create desktop application to upload file (possible file size: 100MB - 1GB)?
  3. If it would be desktop application, it's better to send data directly to Hadoop or somehow through web application?
  4. Can you point me some useful framework/tool/API/resources for uploading from external resources (my web app or desktop application)?
  5. How to use in right way the Hadoop data? Let's assume that user's file comes to Hadoop. I know that I can run Mappers and Reducers on this file what produces output file (or puts some data to HBase - I'm right?). To get this data I need proper output file or get some "SELECT" from HBase, am I right? Does Hadoop contain any trigger to send info to external web app when job is done?

I appreciate every hint in this topic.

Cloning a gem to a local file isn't detecting my changes

Posted: 08 Jul 2016 06:46 AM PDT

I need to make changed to the Twitter gem, so I cloned it to a local folder, then changed my bundle file like so:

gem 'twitter', :path => '~/code/twitter-ruby'  

I added a new method, and ran a test that simply calls the method, to start off with. But I get an error of undefined method. In other words, it hasn't detected my changes. I tried commenting out a whole file, ran my other tests and those all worked, as though the file were still there.

In my project I'm still importing as require 'twitter'.

I've tried running bundle update twitter, I've tried removing it from the bundle, I've tried increasing the version number (which it does detect, and updates to the most recent version), I've tried committing my changes to GIT. Nothing seems to work - I just keep getting the same undefined method error. Any ideas?

EDIT: my Gemfile.lock:

PATH    remote: /Users/Andrew/code/twitter    specs:      twitter (5.15.0)  GEM    remote: https://rubygems.org/    specs:    PLATFORMS    ruby    DEPENDENCIES      twitter!    BUNDLED WITH     1.12.4  

Convert UTF-8 string to readable string

Posted: 08 Jul 2016 05:49 AM PDT

I have a UTF-8 string like:

a= for ccps ‘the way forward’

And want to convert to for CCPs 'the way forward'

I tried code like:

CGI.escape a

before_action with "or" statement

Posted: 08 Jul 2016 07:13 AM PDT

I have several different user types within my application. I was trying to do something like this when accessing a controller;

class Admins::ProgrammesController < ApplicationController    # only allow entry if the user is one of these types.    before_action :authenticate_admin! || :authenticate_super_admin! || :authenticate_programme_leader! || :authenticate_caseworker!      def index    end  

To check the users type is allowed to access this controller.

Alas, that does not seem to be right. Rails only pays attention to the first before_action argument - checks if the user is admin. So my spec does not pass if user is caseworker for example.

How can I achieve this in a similar way?

UPDATE

As requested, more code..

This is my failing spec;

RSpec.describe Admins::ProgrammesController, :type => :controller do    context 'authenticated user' do      before :each do        @user = FactoryGirl.create :caseworker        sign_in @user      end        describe 'GET index' do        it 'responds with a 200 OK status code' do          get :index          expect(response).to have_http_status(:success)        end      end    end  end  

I am 100% confident that the Casework type user is being created. Here is the factory;

FactoryGirl.define do    factory :caseworker, class: 'Users::Caseworker' do      email { "me@example.com" }      password { "password" }    end  end  

Here is the relevant lines from the routes file;

Rails.application.routes.draw do    devise_for :users, controllers: {sessions: 'users/sessions'}, skip: :registrations    devise_for :admins, class_name: 'Users::Admin'    devise_for :caseworker, class_name: 'Users::Caseworker'    devise_for :cardholder, class_name: 'Users::Cardholder'    devise_for :programme_leader, class_name: 'Users::ProgrammeLeader'    devise_for :super_admin, class_name: 'Users::SuperAdmin'      scope module: 'admins' do      # this is the route in question...      resources :programmes, only: [:index, :show, :new]  

My carousel pictures won't show up on the slider. I get a 'GET local_image_path 404(not found)' error on my browser

Posted: 08 Jul 2016 06:05 AM PDT

I am using the carousel slider for my one page app. Everything works perfectly, the only issue is that the pictures won't show up when I run the server. On the browser it gives me an error 'GET http://localhost:3000/assets/images/car.jpg 404 (Not Found)' for each of the images, with its respective path. I have tried most of the solutions online, yet nothing seems to work.

<body>          <div class="carousel-container">              <div id="myCarousel" class="carousel slide" data-ride="carousel">      <!-- Indicators -->      <ol class="carousel-indicators">        <li data-target="#myCarousel" data-slide-to="0" class="active"></li>        <li data-target="#myCarousel" data-slide-to="1"></li>        <li data-target="#myCarousel" data-slide-to="2"></li>        <li data-target="#myCarousel" data-slide-to="3"></li>      </ol>        <!-- Wrapper for slides -->      <div class="carousel-inner" role="listbox">        <div class="item active">          <img src="../assets/images/VedadoPoster.jpg" alt="Poster" />        </div>          <div class="item">          <img src="../assets/images/car.jpg" alt="Car" />        </div>          <div class="item">          <img src="../assets/images/beach.jpg" alt="Beach" />        </div>          <div class="item">          <img src="../assets/images/pool.jpg" alt="Flower"/>        </div>      </div>        <!-- Left and right controls -->      <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>        <span class="sr-only">Previous</span>      </a>      <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>        <span class="sr-only">Next</span>      </a>    </div>  </div>  </body>  

NoMethodError Omniauth Facebook in Rails project

Posted: 08 Jul 2016 06:05 AM PDT

I got some problem with OmniAuth FaceBook login into my webapp. Tell me please, what should i edit to fix this error? Check the code.

Error in the browser:

undefined method `to_a' for "Name Surname":String

User.rb:

def self.from_omniauth(auth)      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|        x = auth.info.name.to_a        user.name = x[0]        user.surname = x[1]        user.login = auth.info.uid        user.email = auth.info.email        user.password = Devise.friendly_token[0,20]        end    end  

Omniauth_callback_controller.rb :

def facebook      if request.env["omniauth.auth"].info.email.blank?        redirect_to "/users/auth/facebook?auth_type=rerequest&scope=email"      end      @user = User.from_omniauth(request.env["omniauth.auth"])      if @user.persisted?        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated        set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?      else        session["devise.facebook_data"] = request.env["omniauth.auth"]        if(@user.surname.nil?)          redirect_to new_profile_path        else          redirect_to my_profile_path        end      end    end  

devise.rb :

config.omniauth :facebook, '*********', '*********', {:client_options => {:ssl => {:verify => false}}}  

Ruby on Rails 4, stylesheets and pictures

Posted: 08 Jul 2016 05:03 AM PDT

Im learning Ruby on Rails using a book, based on RoR 3, unfortunately, I see that some things are different since the last update of the framework. I really dont understand how to use CSS files, js plugins and include Pictures. I see that there is three different assets folders and I understand that we use them according to what we want to do? Concretely, I'm trying to add a css stylesheet and loading it by the application.html.erb file, to add it to my product page. Thanks for your help.

sql, cout number of childrens per each campaigns ancestry

Posted: 08 Jul 2016 06:02 AM PDT

how to count in sql number of children per name in ancestry like tree structure

ID | NAME                    | PATH  100 | Electronics & Computers | /100  101 | Games                   | /100/101  102 | Xbox360                 | /100/101/102  103 | PS4                     | /100/101/103  

so i should have something like

100 | 3  101 | 2  102 | 0  103 | 0  

thanks much for help

Read a csv file containing special characters(different spoken language)

Posted: 08 Jul 2016 04:58 AM PDT

I'm writing a csv file in Hindi(language), when I parse it I get different results.

For example, I make below csv file.

1234444070;आज आप कैसे हैं???  

When I read the same file using open(csv_aws_url).read. I get:

"1234444070;\xE0\xA4\x86\xE0\xA4\x9C \xE0\xA4\x86\xE0\xA4\xAA \xE0\xA4\x95\xE0\xA5\x88\xE0\xA4\xB8\xE0\xA5\x87 \xE0\xA4\xB9\xE0\xA5\x88\xE0\xA4\x82???\r\n"  

Can this happen that I read the same contents while parsing?

What is the most performant way to test cancan abilities that are based on attributes of a parent model?

Posted: 08 Jul 2016 04:45 AM PDT

CanCan allows you to define abilities based on the attributes of a parent model.

For example

can :manage, Address, house: { user_id: @user.id }  

But what is the most performant way to write a test for this?

subject(:ability){ Ability.new(current_user) }  let(:current_user){ nil }  let(:other_user){ nil }    owned_house = House.create(user_id: current_user.id)  other_house = House.create(user_id: other_user.id)    is_expected.to have_abilities( :manage, Address.new(house_id: owned_house.id) )  is_expected.to not_have_abilities( :manage, Address.new(house_id: other_house.id) )  

Is there a better way to do this that does not require House to be written to the database?

No comments:

Post a Comment