Friday, August 19, 2016

Overlay image with text, save, and share | Fixed issues

Overlay image with text, save, and share | Fixed issues


Overlay image with text, save, and share

Posted: 19 Aug 2016 07:35 AM PDT

We are looking into a solution that:

  1. takes a user uploaded image
  2. allows users to enter some text
  3. applies the text as an image overlay over the original image and exports the final image so users can share

We've seen some examples such as https://nisolo.com/pages/inmynisolos, https://www.hillaryclinton.com/trumpyourself/, and http://www.corepoweryoga.com/whyiyoga but we couldn't figure out if they are customized solutions, a paid solution, or just some javascript widget? Anyone have suggestions? We are using Ruby on Rails.

rails csv import ram consumption issue postgres

Posted: 19 Aug 2016 07:37 AM PDT

I have implemented the CSV import in my rails app. Now the issue is ram consumption is too high. The total no. of records in my CSV is around 3600 and my ram consumption is going around 600MB - 800MB and it doesn't even get flushed after coming out of the import method.

I can see similar issue in roo issue list https://github.com/roo-rb/roo/issues/179

I am working on Rails 4.2.6 Ruby 2.2.4

code:

data = CSV.foreach(file.path, headers: true)    data.each do |row|        Model.create(row ....)        .........    end  

Initially my ram consumption is:

GetProcessMem:0x7fd3083b2a30 @mb=204.52734375  

Before getting out of the method:

GetProcessMem:0x7fd30ae1a7a0 @mb=289.60546875  

After completing and redirecting to home page:

GetProcessMem:0x7fd2fb3913d8 @mb=629.61328125  

With this much ram consumption, I cannot deploy it on heroku. This consumed ram doesn't even gets cleaned up, have to restart my server for it.

Anyone up with a solution or any alternative way to import csv.

Error: application.yml not found, see config/application.yml.example

Posted: 19 Aug 2016 07:03 AM PDT

I am running my ruby on rails application and it was working fine. Because of some application requirement I had to make the changes in my application.yml file in config folder. So I did those changes in application.yml.example file and then replaced the existed application.yml file with application.yml.example.

So the new application.yml have all the modification which I wanted . But after this when I am running my application Phusion passenger is giving me error:

application.yml not found, see config/application.yml.example  

But the application.yml is present in my application , i have just modified its content.

Full Error:

  /opt/cnmc-sparc-request-master-june/config/initializers/audit_trail.rb:27:in `rescue in <top (required)>'    /opt/cnmc-sparc-request-master-june/config/initializers/audit_trail.rb:23:in `<top (required)>'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:268:in `load'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:268:in `block in load'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:240:in `load_dependency'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/activesupport-4.2.4/lib/active_support/dependencies.rb:268:in `load'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:652:in `block in load_config_initializer'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/activesupport-4.2.4/lib/active_support/notifications.rb:166:in `instrument'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:651:in `load_config_initializer'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:615:in `each'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/engine.rb:615:in `block in <class:Engine>'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/initializable.rb:30:in `instance_exec'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/initializable.rb:30:in `run'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/initializable.rb:55:in `block in run_initializers'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:226:in `block in tsort_each'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:418:in `block (2 levels) in each_strongly_connected_component_from'    /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:427:in `each_strongly_connected_component_from'    /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:417:in `block in each_strongly_connected_component_from'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/initializable.rb:44:in `each'    /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/initializable.rb:44:in `tsort_each_child'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:411:in `call'    /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:411:in `each_strongly_connected_component_from'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:347:in `block in each_strongly_connected_component'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:345:in `each'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:345:in `call'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:345:in `each_strongly_connected_component'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:224:in `tsort_each'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/2.1.0/tsort.rb:205:in `tsort_each'   /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/initializable.rb:54:in `run_initializers'   /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/application.rb:352:in `initialize!'   /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/railtie.rb:194:in `public_send'   /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/railties-4.2.4/lib/rails/railtie.rb:194:in `method_missing'   /opt/cnmc-sparc-request-master-june/config/environment.rb:25:in `<top (required)>'  config.ru:23:in `require'  config.ru:23:in `block in <main>'  /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'  /opt/cnmc-sparc-request-master-june/vendor/bundle/ruby/2.1.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'  config.ru:1:in `new'  config.ru:1:in `<main>'  /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/passenger-5.0.29/src/helper-scripts/rack-preloader.rb:110:in `eval'  /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/passenger-5.0.29/src/helper-scripts/rack-preloader.rb:110:in `preload_app'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/passenger-5.0.29/src/helper-scripts/rack-preloader.rb:156:in `<module:App>'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/passenger-5.0.29/src/helper-scripts/rack-preloader.rb:30:in `<module:PhusionPassenger>'   /home/mskhan2/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/passenger-5.0.29/src/helper-scripts/rack-preloader.rb:29:in `<main>'  

Model Structure & has_many Association Migrations

Posted: 19 Aug 2016 07:22 AM PDT

I'm trying to set up models in such a way that Users can create Lessons and then other users can sign up for them.

Right now my models are set up like this:

class Lesson < ApplicationRecord    belongs_to :teacher, class_name: 'User'    has_many :students, class_name: 'User'  end    class User < ApplicationRecord    has_many :lessons    has_many :students, :through => :lessons  end  

I want to be able to access the users signed up for a lesson by @lesson.students for example. I'd also like to be able to get all the lessons that a student is participating in (can't really see how I'd do this with my current set up).

Are my model associations right for how I'd like to use them? If so, how can I create the migrations to add the necessary references to my database models?

How can I get a mixed hash of has_many relationships

Posted: 19 Aug 2016 06:55 AM PDT

The User table has_many posts, seeds & areas.

I'm trying to get these all in the same array so I can loop through them ordered by the date they were created.

I have seen .reflect_on_association which appears to do this.. however I have more has_many associations which I don't want to be in the array.

Any thoughts on the best way to do this? I'm trying to avoid getting them all separately like:

posts = user.posts  seeds = user.seeds  areas = user.areas    Hash... posts, seeds, areas  

Can I do something like:

posts_seeds_areas = user.reflect_on_association(:has_many, {Post, Seed, Area})  

Is what I'm suggesting possible?

One rails application, two domains, different session for each

Posted: 19 Aug 2016 07:40 AM PDT

I have one application, with two different domains. They cross in User model. I have Devise for sign in/out. How to make session for each domain?

Rails 5 crash in .erb file but only when running on server

Posted: 19 Aug 2016 06:29 AM PDT

so i have this code in my erb file:

<% a = ["Apple","Orange","Banana","Carrot","Turnip","Rabbit","Lion"] %>  <% arr = @things.where(:active => 1).sort_by{|el| a.index(el[:name])}%>  <% for product in arr %>  

and its crashing on line 2 with this error:

comparison of Fixnum with nil failed  

I replaced it with this:

<% arr = @things.sort_by{|el| a.index(el[:name])}%>  

and its still crashing... when i change the entire code block with this:

<% for thing in @things %>  

the crash goes away. its odd because it runs fine locally.

Alter regex markup to not separate float numbers (like 2.0)

Posted: 19 Aug 2016 07:31 AM PDT

I was looking for a solution to a regex problem in Rails I had and an answer on a separate question lead me 90% of the path to the answer. Basically, what I would like to do is to have a ruby/rails script that will format a messy text in terms of capitalizing every letter after a "./,/!/?". This code by "Mark S"

ng = Nokogiri::HTML.fragment("<p>hello, how are you? oh, that's nice! i am glad you are fine. i am too.<br />i am glad to have met you.</p>")  ng.traverse{|n| (n.content = n.content.gsub(/(.*?)([\.|\!|\?])/) { " #{$1.strip.capitalize}#{$2}" }.strip) if n.text?}  ng.to_s  

The only issue I have with this code, and it is a big issue, is that the code adds a space in between float numbers like "2.0", making a text like:

there is a cat in the hat.it has a 2.0 inch tail!  isn't that awesome?!I think so.  

Become

There is a cat i the hat. It has a 2. 0 inch tail!   Isn't that awesome?! I think so.  

where I obviously want it to be:

There is a cat i the hat. It has a 2.0 inch tail!   Isn't that awesome?! I think so.  

Any suggestions on how to alter this text, for example so that any "." will be ignored by this code?

Get custom value in view hook

Posted: 19 Aug 2016 07:15 AM PDT

I added a custom value in the user form in my redmine. It's a boolean value (a checkbox). My custom value's id is 8

I'm trying to get it's value in a view hook (view_issues_show_description_bottom)

So with this code in my hook class :

cv = CustomValue.where('custom_field_id = 8').first  context[:cv] = cv  

And this code in my .view file

<% if cv.value == "1" %>  

At the beginning it worked, but then after that i added other fields, and it's not working anymore.

I guess there is a better way to get the custom value from the current user ? I'm a complete beginner with ruby so i really don't know how to fix this.

Thx a lot

Specs failing when setting OJ as default OJ serializer

Posted: 19 Aug 2016 05:41 AM PDT

We are attempting to swap our default ruby serializer out with the Optomised JSON serializer (OJ). Got some weird cases where specs are failing because of encoding issues. This has stumped me a bit as I would not assume this would cause any change to encodings

21.3) Failure/Error: @lines ||= source.split("\n")          ArgumentError:         invalid byte sequence in US-ASCII       # /Users/donovan.thomson/.rvm/gems/ruby-1.9.3-p545@quattro/gems         /fuubar-2.0.0/lib/fuubar.rb:67:in `example_failed'  

Any suggestions how to get around this or where to look for possible causes ?

Mirroring Heroku Timeout parameters in local development app

Posted: 19 Aug 2016 05:39 AM PDT

I have a rails app that compiles a large set of PDF reports by making calls to salesforce database.

As it's run once in a blue moon I'm hoping I can sneak this in on the Free Tier and convince the holders of purse-strings to upgrade to hobby once I can demonstrate it.

Currently the app works in production but fails (pretty sure it's a h12) after a consistent interval when in production on Heroku. This will be because I haven't got around to implementing the heavy lifting as a background-job/delayed-job yet, will follow along here and here.

I'm new to the background job API, so ideally I'd like to be able to set up RSpec tests and prod around myself with my development app set up to mirror production constraints of the heroku app. So, questions:

  1. Should I be trying this? Mirroring production constraints in my development app seems like a good way to learn and test this stuff locally... but I have an itching idea they're separate for a reason and I'm violating some boundary or missing a more obvious solution (test on production... but locally?)
  2. How best to mirror the Heroku production constraints (ideally I'd want to be able to test locally if a process seems to be regularly outstripping a Rack or Puma timeout window or worse going over memory limits (I have some pretty heavy objects in there!) and fail in a comparable way so I can work on how to handle/mitigate such failures.
  3. I presume this problem is more universal (constraints of production server differ from dev) than just cos I want to generate PDFs whilst being a cheapskate on Heroku's free tier... does anyone have any good recommendations/reading on best pratice for testing and minimising failures when pushing to production? (I've already run into precompiling assets fun, I'm sure there's other landmines out there somewhere...)

Many thanks!

RabbitMQ Timeout::Error: IO timeout when reading 7 bytes

Posted: 19 Aug 2016 06:46 AM PDT

I use Ubuntu14.04, Rail 5, RabbitMQ (server 3.6.5), Bunny 2.5.1

I implemented Rabbit to servise, and tried to test it.

I wrote next ruby script:

def rabbit_test    s_time = Time.current    10_000.times do |n|      Mq::RabbitService.new('test_queue').publish(n.to_s)    end    p "###############################"    p "RabbirMQ Diff: #{Time.current - s_time}"    p "###############################"  end  

where Mq::RabbitService service include initialize Bunny, connection, creating queue etc

it other terminal I run

Mq::RabbitService.new('test_queue').subscribe  

for start it works good, but I can push ONLY 827 messages (I don't know why exactly 837, but it is constantly same number).

After that my publisher raise error:

[8] pry(main)> rabbit_test  E, [2016-08-19T15:17:02.445820 #6409] ERROR -- #<Bunny::Session:0x6fb39858 oleg@192.168.1.67:5672, vhost=/, addresses=[192.168.1.67:5672]>: Got an exception when receiving data: IO timeout when reading 7 bytes (Timeout::Error)  Timeout::Error: IO timeout when reading 7 bytes  from /home/oleg/.rvm/gems/ruby-2.3.1/gems/bunny-2.5.1/lib/bunny/cruby/socket.rb:52:in `rescue in read_fully'  

Also I've tried: add new user with admin privileges, tried add IP instead localhost address (like 192.168.0.11) result the same.

EDITED

I use my service for RabbitMQ connection Mq::RabbitService gist

BUT

def rabbit_test    s_time = Time.current    1_000.times do |n|      connection = Bunny.new(host: '192.168.1.67', port: 5672, user: 'oleg', password: '111111').start      channel = connection.create_channel      channel.queue('queue_name', auto_delete: true)      exchange = channel.default_exchange      exchange.publish(n.to_s, routing_key: 'queue_name')      channel.close    end    p "###############################"    p "RabbirMQ Diff: #{Time.current - s_time}"    p "###############################"  end  

doesn't work too

Maybe someone know what I do wrong?

Thanks

Michael Hartl Rails Tutorial 4, micropost Partial and instance variables

Posted: 19 Aug 2016 07:22 AM PDT

following his tutorial, the home page from Static-Pages Controller renders a partial_form:

<%= render 'shared/micropost_form' %>   

StaticPagesController.rb

def home    @micropost  = current_user.microposts.build #for the form_form     @feed_items = current_user.feed.paginate(page: params[:page])  end  

Then, in the MicropostController.rb, an action for the partial micropost_form is declared:

class MicropostsController < ApplicationController    def create      @micropost = current_user.microposts.build(micropost_params)      if @micropost.save        flash[:success] = "Micropost created!"        redirect_to root_url      else        @feed_items = []        render 'static_pages/home'      end    end  end  

Notice how, if micropost_form success, it gets redirected static_pages's index view, but, if failed, it renders static_pages home view (which also keeps the params in the form, so the user doesn't have to writype all the data), BUT, it needs to initialize static_pages's home controller instance variables (namely, feed_items).

Now, suppose StaticPages Controller's home has a long list of complex instances variables, how can MicropostController render (to keep form data upon failure) static_pages/home without creating that many instance variables?

note: this question is related to my previous one,but I wanted to understand this basic example before.

Rails 5 enum inside model's Concerns generates NameError: uninitialized constant

Posted: 19 Aug 2016 06:44 AM PDT

Rails 5 here.

I tried without luck to load a concern inside my User model (devise model). The include Levelable works without any problem on other models. Do I have to configure a special config/helper/initializer regarding this special model to make it work?

Model concern Levelable is used by models User and Client

#models/concerns/levelable.rb   require 'active_support/concern'        module Levelable        extend ActiveSupport::Concern      included do      enum level: { beginner: 0, intermediate: 1, advanced: 2, very_advanced: 3 }    end  end  

And the model (shortened for readability)

#models/user.rb  class User < ApplicationRecord      # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable      include Levelable      acts_as_messageable  end  

This setup result is a: NameError: uninitialized constant User::Levelable Same error happens on Client model so I guess something is not working with my concerns load. I already tried to autoload the path inside config/application.rb without any change.

I can not figure out how to make the load of the Concerns works, any help would be great. Thank you !

Getting 400 status from nginx while posting a form with multiple file fields

Posted: 19 Aug 2016 05:45 AM PDT

I am using rails 4.2 and nginx in my production. I have a form with multiple file fields. Till yesterday, this functionality has been working as expected. But a strange issue just arrived.

Issue is: while posting this form, it gets loading. I checked the error log of nginx, did not find anything. While checking the access log, I got the 400 status for that request after timed out.

I have inspected by disabling the file fields. If in that form, one file field is active, then it works. But activating more than one file field such error occurred.

000.11.221.162 - - [19/Aug/2016:11:41:16 +0000] "POST /categories HTTP/1.1" 400 0 "http://someapp.com/categories/new" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"  

Has anyone faced such type of issue. Any suggestion will be helpful.

nginx configuration

server {          listen                80;          server_name           xxx.xxx.xxx.xx;          passenger_enabled     on;          root                  /path/to/rails/public;          rails_env             production;          client_max_body_size    0;          client_body_timeout     600s;          send_timeout            600s;      }  

How to get output from Rails Runner?

Posted: 19 Aug 2016 04:38 AM PDT

I'm working on a Rails Runner script and I want to see what values are set in a variable in the script?

Usual puts doesn't work...

How to combining two search parameters in Rails

Posted: 19 Aug 2016 04:34 AM PDT

I am just getting into Rails and want to preform a simple search FROM destination TO destination. I have the basic search functionality working and connected to the database but when I choose FROM and TWO the output is combined and I get all transports FROM the specific text and all transports TO the specific text. I want to filter them and only have the ones that go FROM TO.

Here is what I have so far.

class Transport < ApplicationRecord  def self.searchfrom(searchfrom)    where("strtloc LIKE ?", "%#{searchfrom}%")   end    def self.searchto(searchto)    where("endloc LIKE ?", "%#{searchto}%")   end  end  

I basically want to add AND in between the two parameters but I am stuck.

This is my transports_controller.rb

if params[:searchfrom]    @transports = Transport.searchfrom(params[:searchfrom])  else    @transports = Transport.all  end    if params[:searchto]    @transports = Transport.searchto(params[:searchto])  else    @transports = Transport.all  end  

I also want the ability to only select FROM. So I cant really do a simple AND statement. But one at a time.

Any help apreciated!

how to do form_for with dynamic, multi-level hash?

Posted: 19 Aug 2016 04:48 AM PDT

I have a class with dynamic content. I initialize it in the new method in the controller:

def new    @person = Person.new(:info => {:first_name => "Joe", :last_name => "Smith"})  end  

Now, disregard the fact that I'm manually coordinating the structure of :info between my controller and form (I have a meta configuration stored in another class, I'm simplifying this to seek abstract help), how do I set up a field for first_name and last_name? This fails:

<%= form_for @person do |f| %>      <% f.text_field :info[:first_name] %>  <% end %>  

It fails with

no implicit conversion of Symbol into Integer  

Thanks for any help.

rake command not running from cron job but works otherwise

Posted: 19 Aug 2016 06:51 AM PDT

Operating System: Ubuntu installed on a docker.

Dockerfile:

FROM ruby    ENV NECESSARY_LIBS git cron nano    # Update and install all of the required packages.  RUN apt-get -qq update && \      apt-get upgrade --assume-yes && \      apt-get install --assume-yes $NECESSARY_LIBS    RUN mkdir /home/deploy  WORKDIR /home/deploy    ENTRYPOINT ["bash"]  

After this I just git cloned the rails app and ran bundle install, it installed everything and rake command is working correctly from command line.

I am running this cron job:

*/5 * * * * /bin/bash -l -c "cd /home/deploy/railsapp && rake spec >> cron.log 2>&1"  

Its running but getting an error: I am getting this in the logfile cron.log:

rake aborted!  Bundler::GemNotFound: Could not find rake-11.2.2 in any of the sources  /home/deploy/railsapp/config/boot.rb:3:in `<top (required)>'  /home/deploy/railsapp/config/application.rb:1:in `<top (required)>'  /home/deploy/railsapp/Rakefile:4:in `<top (required)>'  LoadError: cannot load such file -- bundler/setup  /home/deploy/railsapp/config/boot.rb:3:in `<top (required)>'  /home/deploy/railsapp/config/application.rb:1:in `<top (required)>'  /home/deploy/railsapp/Rakefile:4:in `<top (required)>'  (See full trace by running task with --trace)  

Getting above same errors for /usr/local/bin/rake spec as well (for cron not command line ofcourse).

On running rake spec manually from the command line its working fine, but from cron it is giving this error. Any ideas ?

Edit: On running with bundle exec:

Cron:

*/5 * * * * /bin/bash -l -c "cd /home/deploy/railsapp && bundle exec rake spec >> cron.log 2>&1"  

Log:

bundler: failed to load command: rake (/usr/local/bin/rake)  Bundler::GemNotFound: Could not find rake-11.2.2 in any of the sources    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:95:in `block in materialize'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `map!'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/spec_set.rb:88:in `materialize'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:140:in `specs'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:185:in `specs_for'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/definition.rb:174:in `requested_specs'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/environment.rb:19:in `requested_specs'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/runtime.rb:14:in `setup'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler.rb:95:in `setup'    /usr/local/lib/ruby/gems/2.3.0/gems/bundler-1.12.5/lib/bundler/setup.rb:19:in `<top (required)>'    /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'    /usr/local/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  

Rails - Asking for permission for access to specific infos from User in Oauth provider server?

Posted: 19 Aug 2016 04:15 AM PDT

I have an idea that I am working on and it requires to have my own Opro (oauth provider) server set up. I followed this article which is great and explains clearly. - https://www.sitepoint.com/authenticate-all-the-things-with-opro-the-basics/

Once the user logs in the opro server, they are asked that a particular application is trying to access info and what type of permission user wants to give to app, i.e. to read or write that data.

I want user to be able to select what info application can use. For example, user logs in opro server, they are shown like "Application wants to access your email, contact number, address", each of the attributes as individual checkbox. So I may want to share my email but not other infos. I tick mark just email and proceed ahead and the application works with that. (It would be great if I could make this work not just with user's attributes but across relationships).

Please let me know if I am not clear.

pg_dump: [archiver (db)] connection to database failed: could not connect to server: Connection refused

Posted: 19 Aug 2016 04:15 AM PDT

I'm running a Rails app using Dokku on DigitalOcean and using Rails backup gem to regularly take DB backup. Recently I moved the app from one droplet to another (changed the region) and then the backup is failing to connect to the DB.

Backup model (/root/Backup/models/oktob_database_backup.rb)

Model.new(:oktob_database_backup, 'Oktob Production Database Backup') do      ##    # PostgreSQL [Database]    #    database PostgreSQL do |db|      db.name               = ENV['DATABASE_NAME']      db.username           = ENV['DATABASE_USERNAME']      db.password           = ENV['DATABASE_PASSWORD']      db.host               = ENV['DATABASE_HOST']      db.port               = ENV['DATABASE_PORT']    end      ##    # Amazon Simple Storage Service [Storage]    #    store_with S3 do |s3|      # AWS Credentials      s3.access_key_id     = ENV['AWS_ACCESS_KEY_ID']      s3.secret_access_key = ENV['AWS_SECRET_ACCESS_KEY']      s3.region            = "us-west-2"      s3.bucket            = ENV['AWS_DATABASE_BACKUP_BUCKET_NAME']      s3.path              = "/"    end      ##    # Gzip [Compressor]    #    compress_with Gzip      ##    # Mail [Notifier]    #    # The default delivery method for Mail Notifiers is 'SMTP'.    # See the documentation for other delivery options.    #    notify_by Mail do |mail|      mail.on_success           = true      mail.on_warning           = true      mail.on_failure           = true        mail.from                 = ENV['EMAIL_ADDRESS']      mail.to                   = ENV['EMAIL_ADDRESS']      mail.address              = "smtp.gmail.com"      mail.port                 = 587      mail.domain               = "oktob.io"      mail.user_name            = ENV['SMTP_USERNAME']      mail.password             = ENV['SMTP_PASSWORD']      mail.authentication       = "plain"      mail.encryption           = :starttls    end  end  

The configurations are stored in /etc/environment

## Database  export DATABASE_NAME=''  export DATABASE_USERNAME=''  export DATABASE_PASSWORD=''  export DATABASE_HOST=''  export DATABASE_PORT=''    ## Amazon S3  export AWS_ACCESS_KEY_ID=''  export AWS_SECRET_ACCESS_KEY=''  export AWS_DATABASE_BACKUP_BUCKET_NAME=''    ## Email  export EMAIL_ADDRESS=''  export SMTP_USERNAME=''  export SMTP_PASSWORD=''  

Error message:

2016/08/19 11:04:34][info] Performing Backup for 'Oktob Production Database Backup (oktob_database_backup)'!  [2016/08/19 11:04:34][info] [ backup 4.2.2 : ruby 2.0.0p647 (2015-08-18 revision 51631) [x86_64-linux] ]  [2016/08/19 11:04:34][warn] Cleaner::Error: Cleanup Warning  [2016/08/19 11:04:34][warn]   The temporary packaging folder still exists!  [2016/08/19 11:04:34][warn]   '/root/Backup/.tmp/oktob_database_backup'  [2016/08/19 11:04:34][warn]   It will now be removed.  [2016/08/19 11:04:34][warn]  [2016/08/19 11:04:34][warn]   Please check the log for messages and/or your notifications  [2016/08/19 11:04:34][warn]   concerning this backup: 'Oktob Production Database Backup (oktob_database_backup)'  [2016/08/19 11:04:34][warn]   The temporary files which had to be removed should not have existed.  [2016/08/19 11:04:34][info] Database::PostgreSQL Started...  [2016/08/19 11:04:34][info] Using Compressor::Gzip for compression.  [2016/08/19 11:04:34][info]   Command: '/bin/gzip'  [2016/08/19 11:04:34][info]   Ext: '.gz'  [2016/08/19 11:04:34][error] Model::Error: Backup for Oktob Production Database Backup (oktob_database_backup) Failed!  [2016/08/19 11:04:34][error] --- Wrapped Exception ---  [2016/08/19 11:04:34][error] Database::PostgreSQL::Error: Dump Failed!  [2016/08/19 11:04:34][error]   Pipeline STDERR Messages:  [2016/08/19 11:04:34][error]   (Note: may be interleaved if multiple commands returned error messages)  [2016/08/19 11:04:34][error]  [2016/08/19 11:04:34][error]   pg_dump: [archiver (db)] connection to database "oktob" failed: could not connect to server: Connection refused  [2016/08/19 11:04:34][error]    Is the server running on host "172.17.0.1" and accepting  [2016/08/19 11:04:34][error]    TCP/IP connections on port 5432?  [2016/08/19 11:04:34][error]   The following system errors were returned:  [2016/08/19 11:04:34][error]   Errno::EPERM: Operation not permitted - 'pg_dump' returned exit code: 1  [2016/08/19 11:04:34][error]  [2016/08/19 11:04:34][error] Backtrace:  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/lib/backup/database/postgresql.rb:72:in `perform!'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/lib/backup/model.rb:269:in `each'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/lib/backup/model.rb:269:in `block in perform!'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/lib/backup/model.rb:268:in `each'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/lib/backup/model.rb:268:in `perform!'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/lib/backup/cli.rb:156:in `perform'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/thor-0.18.1/lib/thor/command.rb:27:in `run'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/thor-0.18.1/lib/thor/invocation.rb:120:in `invoke_command'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/thor-0.18.1/lib/thor.rb:363:in `dispatch'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/thor-0.18.1/lib/thor/base.rb:439:in `start'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/gems/backup-4.2.2/bin/backup:5:in `<top (required)>'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/bin/backup:23:in `load'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/bin/backup:23:in `<main>'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/bin/ruby_executable_hooks:15:in `eval'  [2016/08/19 11:04:34][error]   /usr/local/rvm/gems/ruby-2.0.0-p647/bin/ruby_executable_hooks:15:in `<main>'  [2016/08/19 11:04:34][warn] Cleaner::Error: Cleanup Warning  [2016/08/19 11:04:34][warn]   The temporary packaging folder still exists!  [2016/08/19 11:04:34][warn]   '/root/Backup/.tmp/oktob_database_backup'  [2016/08/19 11:04:34][warn]   This folder may contain completed Archives and/or Database backups.  [2016/08/19 11:04:34][warn]  [2016/08/19 11:04:34][warn]   Make sure you check these files before the next scheduled backup for  [2016/08/19 11:04:34][warn]   'Oktob Production Database Backup (oktob_database_backup)'  [2016/08/19 11:04:34][warn]   These files will be removed at that time!  [2016/08/19 11:04:34][info] Sending notification using Notifier::Mail...  

The app is working properly, but not sure what happened for the backup after the move. I tried to restart the DB container and the man app, but something is missing.

Simple form not submitting to database

Posted: 19 Aug 2016 04:15 AM PDT

I'm building a simple online shop for practice and want to track order histories, at the moment I'm getting the user to submit but the shipping address and order history, later I'll upgrade order history to be a hidden field.

The problem is that I can't get the simple form to submit anything to my database.

My form looks like this:

<p class="text-center">      congratulations your order is almost complete, please fill out the form below to place your order or <%= link_to "browse other products.", root_path %>    </p>        <%= simple_form_for @placeorder, html: {  multipart: true }  do |f| %>  <%= f.error_notification %>    <div class="form-inputs" >    <%= f.input :shipping_address, label: false, placeholder: 'Shipping address', input_html: { class: 'input-lg', required: true } %>      <%= f.input :order_history, label: false, placeholder: 'order_history', input_html: { class: 'input-lg', required: true } %>   </div>    <div class="form-actions">    <%= f.button :submit, "Confirm order" %>  </div>  <% end %>  

My place order controller looks like this:

class PlaceOrdersController < ApplicationController        def new      current_order.order_items.each do |order_item|       @last_item_name = order_item.product.name      end      @placeorder = PlaceOrder.new      @order = current_order.order_items    end      def create      @placeorder = PlaceOrder.create(place_order_params)      p  "HELLO #{@placeorder}"      if @placeorder.save        flash[:success] = "You've made your order"        redirect_to root_path      else        flash[:alert] = "Something went wrong, check the form and submit your order again"        render :new      end    end      private       def place_order_params      params.require(:place_order).permit(:shipping_address, :order_history)    end    end  

My routes.rb looks like this:

Rails.application.routes.draw do    resources :products    resources :checkout    resources :place_orders    resource :cart, only: [:show]    resources :order_items, only: [:create, :update, :destroy], defaults: { format: 'js' }    root to: "products#index"    devise_for :users, :controllers => { registrations: 'registrations' }  end  

I have other forms that are working fine and they look the same. Any help would be greatly appreciated.

Chartkick: How to pass parameters to the ChartsController

Posted: 19 Aug 2016 04:13 AM PDT

I have created a ChartsController, for the async JSON loading. It is decribed here: https://github.com/ankane/chartkick#say-goodbye-to-timeouts

Everything works fine. But now I try to send a parameter to the controller how can this be done?

This is my call in the view.html.erb:

<%= line_chart test_charts_path %>  

I want something like this:

<%= line_chart test_charts_path(object) %>  

Is this possible?

Get all included Active Record objects of collection

Posted: 19 Aug 2016 03:54 AM PDT

Is there any way of getting all objects, included in Active Relation query? Something like this:

def index    @items = Item.all.includes(:comments)    @comments = @items.comments // No such method for AR Collection :(  end  

The obvious way to get all the items in this case is:

@comments = @items.map(&:comments).flatten.uniq  

Thanks to using .includes(:comments) there should be no N+1 queries, but I worry about the performance of this code. Are there any built-in or more effective ways of getting all included records of collection?

Rails - Flexslider, flexAnimate dynamically

Posted: 19 Aug 2016 03:18 AM PDT

I am using flexslider as;    <div class="car-detail-slideshow2" data-target="#modalFillIn" data-toggle="modal" id="car_popup_pictures">                  <% @car.pictures[0..1].each_with_index do |p1, i| %>                          <div class= "car-show-pop col-sm-6 no-padding cursor-pointer" data-index= "<%= i %>">                              <%= image_tag p1.image_url(:slider).to_s %>                          </div>                  <% end %>                  <% @car.pictures[2..4].each_with_index do |p2, i| %>                          <div class= "car-show-pop col-sm-4 no-padding col-sm-height cursor-pointer" data-index= "<%= i + 2 %>">                              <%= image_tag p2.image_url(:slider).to_s %>                          </div>                  <% end %>                        </div>  

which creates pictures and their indexes, when I click I would like flexslider to open from the data-index.

So far I tried to add it to start function on click of the div no luck Flexslider works, but it starts from the index of 0, does not matter, which data-index I pressed. How can I fix this?

<script type="text/javascript">  $(function(){            $('#modalFillIn').on('shown.bs.modal', function () {       $('#carousel2').flexslider({          animation: "slide",          controlNav: false,          animationLoop: false,          slideshow: false,          itemWidth: 110,          itemMargin: 5,          directionNav: false,          asNavFor: '#slider'      });       $('#slider').flexslider({          animation: "fade",          controlNav: false,          animationLoop: false,          slideshow: false,          touch: true,          keyboard: true,          sync: "#carousel2",s          start: function(slider){            $('body').removeClass('loading');            $('.car-show-pop').click(function(event){              event.preventDefault();              var pos = parseInt($(this).data('index'), 10);                  slider.flexAnimate(pos, true);            });          }    });         });  });  </script>  

Print CSV headers in bold text in Rails

Posted: 19 Aug 2016 04:44 AM PDT

My CSV is getting generated totally correct. I want to print the CSV headers bold. Is there any way to print them in bold.

My code that prints the simple CSV.

<%= CSV.generate do |csv|        csv << ["REF", "Customer Name", "Property Address", "Moving Date", "Mobile Phone", "Operator", "Status"]      @results.each do |result|          csv << [result.id, result.customer_name, result.address_label, result.moving_date.strftime("%b %d, %Y"), "", result.operator.try(:name), result.status ]    end.html_safe  %>  

Thanks in advance!!

Method Error Rails

Posted: 19 Aug 2016 03:08 AM PDT

I've tried to debug this error, but cannot figure out what is wrong with my code.

I am using the devise gem for users and current_user is a devise method

I am trying to add a before action to my documents controller to prevent editing, updating and destroying a document when not the user who has uploaded it.

This is the error: undefined method 'documents' for nil:NilClass

The error is reffering to the private method authorized_user

This is my controller code:

class DocumentsController < ApplicationController  before_action :find_document, only: [:show, :edit, :update, :destroy, :upvote, :dislike]  before_action :authorized_user, only: [:edit, :update, :destroy]  before_filter :authenticate_user!, except: [:index, :show]    def index      if params[:category].blank?          @documents = Document.all.order(:cached_votes_up => :desc)            if params[:search]          @documents = Document.search(params[:search]).order(:cached_votes_up => :desc)          elsif          @documents = Document.all.order(:cached_votes_up => :desc)          end        else          @category_id = Category.find_by(name: params[:category]).id          @documents = Document.where(category_id: @category_id).order(:cached_votes_up => :desc)      end  end    def show  end    def new      @document = current_user.documents.build  end    def create      @document = current_user.documents.build(documents_params)        if @document.save          redirect_to @document      else          render 'new'      end  end    def edit  end    def update      if @document.update(documents_params)          redirect_to @document      else          render 'edit'      end  end    def destroy      @document.destroy      redirect_to root_path  end    private     def documents_params      params.require(:document).permit(:title, :category_id, :search, :pdf)  end    def find_document      @document = Document.find(params[:id])  end    def authorized_user      @document = current_user.documents.find_by(id: params[:id])      redirect_to documents_path, notice: "Not authorized to edit this Document" if @document.nil?  end  end  

I'm not sure why i'm getting the undefined method for the documents

Premailer performance

Posted: 19 Aug 2016 02:49 AM PDT

I am using foundation as front end framework,premailer for rendening inline css in my RoR project.The email content i generate in my application are huge.It takes lot of time to convert CSS inline.

class Premailer    module Adapter      module Nokogiri        def to_inline_css           ....          doc.search(selector).each ...           .....        end      end    end  end  

doc.search(selector) is super slow for huge content in doc.

It takes about 15 -20 seconds to render http://foundation.zurb.com by making CSS inline in http://premailer.dialect.ca/.

Please suggest an efficient way to convert HTML pages with inline css

Rails - How to query by multiple ids(array)

Posted: 19 Aug 2016 03:20 AM PDT

In rails 4, I am trying to access a ActiveRecord relation using multiple ids.

Ids are coming as Parameters: {"ids"=>"[55, 56]"}. In controller I am using it as User.where(:id=>params[:ids]) but this query returns zero results.

View path is like user_posts_path(:ids=>[5, 6])

Right now params[:ids].class.name is String. How to make it only as an array?

Determine which link (on same page) was used?

Posted: 19 Aug 2016 02:42 AM PDT

I have a page with two links to an introduction/registration page. We want to show different content based on which link the user uses. They appear in different contexts on the same page, and we would like to tailor the message on the registration page to that context. For SEO purposes I was told not to change the URL.

I'm using rails. Since the incoming user will have the same referrer regardless of which link was clicked, what is the best way to know which link was used to get to my page? Is it possible in a practical way without altering the URL?

No comments:

Post a Comment