How to Generate Standard Attribute Setters for Rails Posted: 18 Aug 2016 07:46 AM PDT I have many strings in my application's models, each should not contain any leading, trailing and duplicate blanks. In order to ensure this, I created separate attribute setter methods for each attribute: def label=( text ) write_attribute( :label, text.strip.squeeze(' ')) end def description=( text ) write_attribute( :description, text.strip.squeeze(' ')) end ... There should be a more elegant, DRYer way. Including a check for nil. |
I18n how to translate multiple lookup scopes Posted: 18 Aug 2016 07:40 AM PDT How would I translate using multiple scopes?(<-- maybe not to right terminology) Assume I have these two yml files: en.yml en: activerecord: attributes: table_one: field_one: Field one custom.en.yml en: activemodel: attributes: table_one: field_two: Field TWO If I call: I18n.translate(:field_one, :scope => [:activemodel ,:attributes, :table_one]) How do i change this to use a lookup with my translate scope to look under activerecord as well? I have tried: lookups = [] lookups << ["activerecord.attributes.table_one.field_one"] lookups << [:field_one, :scope => [:activerecord, :attributes, :table_one]] lookups << [self.human_attribute_name(:field_one)] I18n.translate(:field_one, :scope => [:activemodel ,:attributes, :table_one], :default => lookups) |
Including dynamic json-ld tags in Rails app Posted: 18 Aug 2016 07:11 AM PDT I have the following snippet in my show.html.erb <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Person", "name": "<%= @person_name %>", "logo": "<%= @person_img_url %>", "membersOf":[ { <%= @person_orgs.each do |group| %> "@context": "http://schema.org", "@type": "Organization", "name": "<%= group[:name] %>" "logo": "<%= group[:img_url] %>", "url": "https://siftery.com/groups/<%= group[:handle] %>" <% end %> } ] } The output which I get membersOf is [{}{}{}] does not turn out to be an array instead a string with missing commas. How should I correct so that membersOf is [{},{},{}] |
Making delayed::job tasks run immediately in development Posted: 18 Aug 2016 07:27 AM PDT How do I configure Delayed::Job to run all delayed methods immediately in development? |
Ruby JBuilder with variable names? Posted: 18 Aug 2016 06:47 AM PDT How do I use a variable name when constructing a JSON using JBuilder in Ruby? For example, suppose I have a variable var1 var1 = "query_string" query = Jbuilder.encode do |json| json.query do json.query_string do json.query "SOMETHING" end end end How can I do something like: json.var1 do Rather than explicitly: json.query_string? |
How to create an object when update another with nested_form (has_many belongs_to association) Posted: 18 Aug 2016 06:45 AM PDT Have two models, Clients and Calls, with a has_many - belogns_to association. I want to create a new call every time a update the client. Using the nested_form, i was able to create it, BUT ITS GENERATING AN EMPTY OBJECT, with no params.... Models.rb class Call < ActiveRecord::Base belongs_to :client has_and_belongs_to_many :interests end class Client < ActiveRecord::Base has_many :calls, :dependent => :destroy belongs_to :user has_and_belongs_to_many :interests accepts_nested_attributes_for :calls end calls_controller.rb class Admin::CallsController < ApplicationController before_action :set_call, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! layout 'admin' # GET /calls def index @calls = Call.order(created_at: :desc) end # GET /calls/1 def show @calls = Call.order(created_at: :desc) end # GET /calls/new def new # @call = Call.new end # GET /calls/1/edit def edit end # POST /calls def create @client = Client.find(params[:client_id]) @call = @client.calls.create(call_params) if @call.save redirect_to [:admin, @client], notice: 'Atendimento criado com sucesso.' @call.create_activity :create, owner: current_user else render :new end end # PATCH/PUT /calls/1 def update # if @call.update(call_params) # redirect_to @call, notice: 'Artigo editado com sucesso.' # else # render :edit # end end # DELETE /calls/1 def destroy @client = Client.find params[:client_id] @call = @client.calls.find params[:id] @call.destroy redirect_to (:back), notice: 'Atendimento excluído.' end private # Use callbacks to share common setup or constraints between actions. def set_call @call = Call.find(params[:id]) end # Only allow a trusted parameter "white list" through. def call_params params.require(:call).permit(:resume, :calltype, :client_id, interest_ids:[]) end end clients_controller.rb class Admin::ClientsController < ApplicationController before_action :set_client, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! layout 'admin' # Clients.paginate(:page => params[:page], :per_page => 30) # GET /clients # GET /clients.json def index @user = current_user @calls = Call.order(created_at: :desc) if @user.admin? @clients = Client.order(created_at: :desc).paginate(:page => params[:page], :per_page => 20) @condition = 'ADMINISTRADOR' @clients_count = Client.count else @clients = @user.clients.order(updated_at: :desc).paginate(:page => params[:page], :per_page => 20) @condition = 'CORRETOR' @clients_count = @user.clients.count end end # GET /clients/1 # GET /clients/1.json def show @client = Client.find(params[:id]) # @calls = Call.order(created_at: :desc) @user = current_user #..... end # GET /clients/new def new @client = Client.new end # GET /clients/1/edit def edit end # POST /clients # POST /clients.json def create @client = Client.new(client_params) if @client.save redirect_to [:admin, @client], notice: 'Obrigado pelo Cadastro, entraremos em contato.' ClientMailer.new_lead(@client).deliver! else render new_admin_client_path, notice: 'OOPS! Há problemas no seu formulário, verifique por favor.' end end # PATCH/PUT /clients/1 # PATCH/PUT /clients/1.json def update if @client.update(client_params) @client.calls.create(@client[:client_id]) redirect_to admin_clients_path(current_user), notice: 'Cliente atribuído ao corretor ' # ClientMailer.client_user_set(@client).deliver_now else render :edit end end # DELETE /clients/1 # DELETE /clients/1.json def destroy @client.destroy redirect_to admin_clients_url, notice: 'Cliente deletado' end private # Use callbacks to share common setup or constraints between actions. def set_client @client = Client.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def client_params params.require(:client).permit(:name, :telephone, :email, :message, :user_id, :origin, :rg, :cpf, :street, :number, :birthday, :attended, interest_ids:[]) end end clients/edit.slim = simple_form_for ([:admin, @client]) do |f| h4 = f.error_notification .row -if current_user.admin? .input-field = f.collection_select :user_id, User.all, :id, :name, { prompt: "Selecione o corretor..." } h3.title Interesses do cliente .input-field = f.collection_check_boxes :interest_ids, Interest.all, :id, :name do |b| .col.s6.m3.collection-check-box = b.check_box = b.label .row = f.simple_fields_for ([:admin, :client, Call.new]) do |c| .input-field#inline = c.input :calltype, collection: ['E-mail', 'Telefone', "WhatsApp"], as: :radio_buttons, label: "" .input-field = c.input :resume, label: 'Resumo do atendimento' .row = f.hidden_field :attended, value: true .input-field.center = f.button :submit, 'Salvar', class: 'btn-large' |
How to watch MySQL database change without Rails app Posted: 18 Aug 2016 06:18 AM PDT MySQL database is two application(PHP, Rails) use I hope in the Rails application watch the PHP insert data can be trigger Rails method. How can I do it. Now I use hair_tigger,But not tigger the PHP app insert data And I can use ruby syntax write SQL syntax, |
Validation Error Messages for belongs_to Assocations made easy Posted: 18 Aug 2016 07:04 AM PDT I have quite some belongs_to associations in my application, some of them are optional (i.e. the association could be nil), some are mandatory (association must be a valid parent record. My initial approach was to validate the given id using my own validation method (here for a mandatory association) belongs_to :category validates :category_id, presence: true validate given_category_exists def given_category_exists if category_id.present? errors.add( :category_id, 'must be present' ) \ Category.exists?( category_id ) end end Then I found out that Rails would do this for me if I would use the presence check on the association so I could omit my own validation method: belongs_to :category validates :category, presence: true But now, the generated error message would simply state: Category can't be blank . The problems here are: (1) Can I provide a more useful message? (2) How can I insert my own translation for the attribute? Category is the default label generated from the validates method, can't be blank is the default error text for :blank. Another problem with this: The related input field in the form is not marked as 'field_with_errors' as this field is identified with the attribute's name, not the association's name. Using the standard way of doing things, I would add an additional attribute to my I18n translation file for the name of the association category and adding a replacement for the standard message: en: activerecord: models: attributes: my_model: category_id: 'This Category' category: 'This Category' errors: models: my_model: attributes: category: blank: 'must be specified.' Lots of lines where things can go wrong. And I did not like the idea to add superficial attributes which are actually not attributes but names of associations. Is there an easier way? |
Rails has_many through order by join fails on includes Posted: 18 Aug 2016 06:32 AM PDT What is the proper way to implement order in a through table so that I can also use it in an includes? It appears you can do this from the docs and some previous questions. However, it is failing when using :includes class DoctorProfile has_many :doctor_specialties has_many :specialties, -> { order 'doctor_specialties.ordinal' }, through: :doctor_specialties class Specialty has_many :doctor_specialties has_many :doctor_profiles, through: :doctor_specialties class DoctorSpecialty < ActiveRecord::Base belongs_to :doctor_profile belongs_to :specialty I'm able to call DoctorProfile.first.specialties which generates the correct SQL. DoctorProfile Load (0.7ms) SELECT "doctor_profiles".* FROM "doctor_profiles" ORDER BY "doctor_profiles"."id" ASC LIMIT 1 Specialty Load (0.6ms) SELECT "specialties".* FROM "specialties" INNER JOIN "doctor_specialties" ON "specialties"."id" = "doctor_specialties"."specialty_id" WHERE "doctor_specialties"."doctor_profile_id" = $1 ORDER BY doctor_specialties.ordinal [["doctor_profile_id", 1]] However, when calling DoctorProfile.includes(:specialties).first I receive the following error: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "doctor_specialties" LINE 1: ...lties" WHERE "specialties"."id" IN (69) ORDER BY doctor_spe... ^ : SELECT "specialties".* FROM "specialties" WHERE "specialties"."id" IN (69) ORDER BY doctor_specialties.ordinal If I remove the order in the has_many relationship I'm able able to successfully make the query DoctorProfile.includes(:specialties).first Why is this failing with the includes? How can I make it work? |
Thinking Sphinx - can't get exact match first Posted: 18 Aug 2016 06:06 AM PDT I have quite simple thinking sphinx setup: Indeces: indexes first_name, :sortable => true indexes last_name, :sortable => true indexes family_name, :sortable => true indexes born_date, :sortable => true indexes death_date, :sortable => true There are some other related models in it but thats not the case. Thats the riddle I use: Riddle::Query.escape( URI.decode(params[:search]) ), :star => true, :per_page => params[:per_page], :page => params[:page], :ranker => :sph04, :match_mode => :phrase, :order => ('death_date DESC') What I'm trying to achieve is exact matches first on the list. Now when I search for "Anna" I get all mixed like "Hanna", "Anna-Lisa" before "Anna". It's even worst when I remove 'order'. I've tried several rankers and mach modes with no luck. I would be perfect if I get exact mach on top and sorted by other attribute (date), and other matches after it, also sorted by date. Only solution that came to my head now is sort by result length (shorter is closer to exact match), but maybe there is some better solution? Any clues how to fix this? |
Rails4 Error: rake aborted! Don't know how to build task 'doc/app/index.html' (see --tasks) Posted: 18 Aug 2016 06:05 AM PDT $ rake db:migrate or $ bundle exec rake db:migrate i am getting error like rake aborted! Don't know how to build task 'doc/app/index.html' (see --tasks) |
How to create select for enum attribute in Rails 4 with simple Form Posted: 18 Aug 2016 06:30 AM PDT I am having a hard time figuring out how to get my select field to work for an enum attribute using Simple_form on a Rails 4.2 app. Here is my model: class Employee < ActiveRecord::Base # returns the full name of the employee. This code is found in a concern called name.rb include Name rolify # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable enum status: [:active, :vacation, :unemployed] enum os: [:mac, :windows] validates :first_name, presence: true, length: {minimum: 2} validates :last_name, presence: true, length: {minimum: 2} validates :email, email: true, presence: true, uniqueness: true validates :paypal_email, email: true, presence: true, uniqueness: true # validates :status, presence: true validates :skype_id, presence: true, uniqueness: true validates :mobile, presence: true, numericality: true, length: {minimum: 10} validates :address, :province_state, :country, :postal_code, :bachelor_degree, :os, presence: true #, , , ,, :os, presence: true end Here is my form: <h2>New Employee Registration Form</h2> <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> <%= f.error_notification %> <div class="form-inputs"> <%= f.input :first_name, required: true, autofocus: true %> <%= f.input :last_name, required: true %> <%= f.input :email, required: true%> <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %> <%= f.input :password_confirmation, required: true %> <%= f.input :paypal_email, required: true%> <%= f.input :mobile, required: true %> <%= f.input :skype_id, required: true %> <%= f.input :address, required: true %> <%= f.input :province_state, required: true %> <%= f.input :country, required: true %> <%= f.input :postal_code, required: true %> <%= f.input :bachelor_degree, required: true %> <%= f.input :os, as: :select, collection: Employee.os.keys, selected: 1, required: true %> <%= f.input :status, as: :select, collection: Employee.status.keys, selected: 1, required: true %> </div> <div class="form-actions"> <%= f.button :submit, "Register New Employee" %> </div> Here is the error I'm getting: Failure/Error: <%= f.input :status, as: :select, collection: Employee.status.keys, selected: 1, required: true %> ActionView::Template::Error: undefined method `status' for # The strange thing is that the exact same code for a similar field just 'os' works perfectly. Appreciate any help to figure out why this attribute produces the error. |
Replace options for select tag rails 4 Posted: 18 Aug 2016 06:44 AM PDT I want to replace the current options for a select tag with the values in an array My form <%= f.select :nick_names,[" "], { prompt: "Select Nicknames" }, { :multiple => true, class: 'selectpicker', required: true } %> In my js I am trying var data = ["robb", "sansa", "arya", "bran", "rickon", "SNOW"] $("#form_nick_names").empty(); //remove all previous options for(i = 0;i<data.length;i++){ $("#form_nick_names").append( $("<option></option>").attr("value", data[i]).text(data[i]) ); } Doesn't seem to work. What am I doing wrong ? |
Clone/use development db data in testing environment in Rails 4? Posted: 18 Aug 2016 05:53 AM PDT I'm not using rspec, I'm just using the built in testing provided by rails 4. I do not want to use fixtures, I only want to use the same data that I generated in my development db, is that possible? |
Docker Compose on Windows 7: Could not locate Gemfile or .bundle/ directory Posted: 18 Aug 2016 05:48 AM PDT I get the following error when I run the command docker-compose up Could not locate Gemfile or .bundle/ directory exited with code 10 Following is the code. Note : I have added the parent directory of my code as a permanent shared folder to the VM using Oracle VM virtual box manager. Any thoughts to resolve the issue.? Dockerfile FROM ruby:2.3.0 ENV HTTP_PROXY http://proxy.com:8080 ENV HTTPS_PROXY http://proxy.com:8080 RUN mkdir /student-api WORKDIR /student-api ADD Gemfile /student-api/Gemfile ADD Gemfile.lock /student-api/Gemfile.lock RUN bundle install ADD . /student-api Docker Compose db: image: postgres ports: - "5432:5432" web: build: . command: bundle exec rails s -p 3000 -b '0.0.0.0' volumes: - .:/student-api ports: - "3000:3000" links: - db |
Access of Parse.com Validations config file Posted: 18 Aug 2016 06:23 AM PDT Currently, I am working on a Ruby on Rails project which uses Parse.com (now self hosted) as database and for the current I am working on I get the validation error/rule which needs to be modified. I believe it is a beforeSave() callback/check on Parse side. How can I access/modify or where to look for (location) this Parse config which holds all the validation rules? Is there something like default collection on a database which holds the validation rules? |
Minitest/Rails: DateTime.now versus DateTime.current in travel_to block Posted: 18 Aug 2016 05:40 AM PDT Is the following behavior of the travel_to test helper a bug or a feature? Either way, why is it happening this way and should DateTime.now be avoided altogether in Rails code? Using ruby (2.3.1), rails (4.2.6) and minitest (5.9.0): test 'traveling to 1900 (Time)' do travel_to Time.new(1916, 1, 1, 7, 0, 0) do puts Time.current puts Time.now puts DateTime.current puts DateTime.now end end => 1916-01-01 07:00:00 UTC 1916-01-01 07:00:00 UTC 1916-01-01T07:00:00+00:00 2016-08-18T14:29:20+02:00 Similarly, test 'traveling to 1900 (DateTime)' do travel_to DateTime.new(1916, 1, 1, 7, 0, 0) do puts Time.current puts Time.now puts DateTime.current puts DateTime.now end end => 1916-01-01 07:00:00 UTC 1916-01-01 07:00:00 UTC 1916-01-01T07:00:00+00:00 2016-08-18T14:29:24+02:00 |
BCrypt authentication always failing RAILS Posted: 18 Aug 2016 05:29 AM PDT I'm following Michael Hartl's Ruby on Rails Tutorial, where I reached Chapter 8. But the authenticated? method always returns false. The Cookie for :remember_token is saved properly. But as i compare the in the database digested remember_digest via BCrypt::Password.new(remember_digest).is_password?(remember_token) it will always return false. I'm using Rails 4.2.5.1. Here is my code: controllers/sessions_controller.rb class SessionsController < ApplicationController def new end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) log_in(user) params[:session][:remember_me] == '1' ? remember(user) : forget(user) redirect_to user else flash.now[:danger] = 'Invalid email/password combination' render 'new' end end def destroy log_out if logged_in? redirect_to root_url end end models/user.rb class User < ActiveRecord::Base attr_accessor :remember_token before_save { email.downcase! } validates :name, presence: true, length: { maximum: 50 } validates :email, presence: true, length: { maximum: 250 }, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i }, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 6 } has_secure_password def self.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end def User.new_token SecureRandom.urlsafe_base64 end def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end def authenticated?(remember_token) return false if remember_digest.nil? BCrypt::Password.new(remember_digest).is_password?(remember_token) end def forget update_attribute(:remember_digest, nil) end end helpers/sessions_helper.rb module SessionsHelper def log_in(user) session[:user_id] = user.id end def log_out forget(current_user) session.delete(:user_id) @current_user = nil end def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent.signed[:remember_token] = user.remember_token end def forget(user) user.forget cookies.delete(:user_id) cookies.delete(:remember_token) end def current_user if (user_id = session[:user_id]) @current_user ||= User.find_by(id: user_id) elsif (user_id = cookies.signed[:user_id]) user = User.find_by(id: user_id) if user && user.authenticated?(cookies[:remember_token]) @current_user = user puts "INSIDE" end end end def logged_in? !current_user.nil? end end |
Using Firebase versus Custom Rails Backend [on hold] Posted: 18 Aug 2016 05:04 AM PDT I'm developing an app that will have basic user authentication and a "connect user" component. I'm thinking of just using firebase because I'm not really a server guy. I've searched for someone to help out for the backend part and was told it would be like 300$/month for server cost even if I don't have any users. First off does that make sense that it would cost 300$/month? Also, couldn't I just use firebase to save money and development time? Thanks |
ActionCable unsubscribe callback not working when iOS client send "unsubscribe" Posted: 18 Aug 2016 05:00 AM PDT Remote iOS client successfully connects to me, send subscribe command (it works fine), but on "unsubscribe" command I get next error: Unsubscribing from channel: {"channel":"Assessor::StationChannel", "station_id": 1} Could not execute command from {"command"=>"unsubscribe", "identifier"=>"{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"}) [NoMethodError - undefined method `unsubscribe_from_channel' for nil:NilClass]: /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:44:in `remove_subscription' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:40:in `remove' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/subscriptions.rb:16:in `execute_command' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/connection/base.rb:88:in `dispatch_websocket_message' | /app/vendor/bundle/ruby/2.2.0/gems/actioncable-5.0.0/lib/action_cable/server/worker.rb:58:in `block in invoke' Subscribe message format: {"command": "subscribe", "identifier": "{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"} Unsubscribe message format: {"command": "unsubscribe", "identifier": "{\"channel\":\"Assessor::StationChannel\", \"station_id\": 1}"} I cannot reproduce this problem on localhost, so maybe somebody can help me? |
ERROR: Error installing rmagick on Redhat 7 Posted: 18 Aug 2016 05:17 AM PDT I am trying to run my Rails application in Redhat7 but facing this error when I run bundle install: An error occurred while installing rmagick (2.13.4), and Bundler cannot continue. Make sure that gem install rmagick -v '2.13.4' succeeds before bundling. When I run gem install rmagick, this is the error I am getting: [root@ip-172-12-13-148 MyProject]# gem install rmagick -v '2.13.4' Building native extensions. This could take a while... ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. current directory: /usr/local/rvm/gems/ruby-2.3.0/gems/rmagick-2.13.4/ext/RMagick /usr/local/rvm/rubies/ruby-2.3.0/bin/ruby -r ./siteconf20160818-2119-1nvxrgu.rb extconf.rb checking for Ruby version >= 1.8.5... yes checking for gcc... yes checking for Magick-config... no checking for pkg-config... yes checking for ImageMagick version >= 6.4.9... yes Package MagickCore was not found in the pkg-config search path. Perhaps you should add the directory containing MagickCore.pc' to the PKG_CONFIG_PATH environment variable No package 'MagickCore' found Package MagickCore was not found in the pkg-config search path. Perhaps you should add the directory containing MagickCore.pc' to the PKG_CONFIG_PATH environment variable No package 'MagickCore' found Package MagickCore was not found in the pkg-config search path. Perhaps you should add the directory containing MagickCore.pc' to the PKG_CONFIG_PATH environment variable No package 'MagickCore' found Package MagickCore was not found in the pkg-config search path. Perhaps you should add the directory containing MagickCore.pc' to the PKG_CONFIG_PATH environment variable No package 'MagickCore' found checking for stdint.h... yes checking for sys/types.h... yes checking for wand/MagickWand.h... no Can't install RMagick 2.13.4. Can't find MagickWand.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=/usr/local/rvm/rubies/ruby-2.3.0/bin/$(RUBY_BASE_NAME) To see why this extension failed to compile, please check the mkmf.log which can be found here: /usr/local/rvm/gems/ruby-2.3.0/extensions/x86_64-linux/2.3.0/rmagick-2.13.4/mkmf.log extconf failed, exit code 1 Gem files will remain installed in /usr/local/rvm/gems/ruby-2.3.0/gems/rmagick-2.13.4 for inspection. Results logged to /usr/local/rvm/gems/ruby-2.3.0/extensions/x86_64-linux/2.3.0/rmagick-2.13.4/gem_make.out I tried using yum install IMageMagick and run bundle, but issue continues.
[root@ip-172-12-13-148 MyProject]# yum install ImageMagick-devel
then: Loaded plugins: amazon-id, rhui-lb, search-disabled-repos No package ImageMagick-devel available. Error: Nothing to do Please help. Please help. |
Find position of text of existing pdf file Posted: 18 Aug 2016 04:49 AM PDT How can I find the position of elements in existing pdf. I tried pdf-reader to do this but not get the proper solution. Basically, I have to find how much margin is given to a text. |
How to override devise routes from plugin Posted: 18 Aug 2016 04:46 AM PDT I am building plugin for my engine which will enable user to login via socials networks like facebook and twitter. I came to a part where i need to override devise user routes from plugin, which i have configured in engine. If i set in dummy application: devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" } I have working omniauth, but i need to load this controller from plugin. How i am supposed to do this? My callbacks controller: class CallbacksController < Devise::OmniauthCallbacksController def facebook @user = MyEngine::User.from_omniauth(request.env["omniauth.auth"]) sign_in_and_redirect @user end def twitter @user = MyEngine::User.from_omniauth(request.env["omniauth.auth"]) sign_in_and_redirect @user end end |
How to add and remove relationship through quries in ruby on rails Posted: 18 Aug 2016 06:15 AM PDT User and Bid are two ActiveRecord models. I want to add add and remove relationship through queries. I tried User.find(1).bids.find(1).destroy , but this deletes the record. Please suggest me solution. |
Tracking stats for API Posted: 18 Aug 2016 04:38 AM PDT I am currently developing a REST API in Rails 5. I am wondering if there is a gem or self-hosted tool (preferably not Google or a service that requires external data sharing) that I can use to provide usage statistics of my API (url, parameters provided, response times, HTTP status and, if possible, user_id etc). My goal with this, is to determine which methods/functionality are used most, how these methods are performing and where I should plan optimizations and refactoring. |
NameError: uninitialized constant IntegrationTest Posted: 18 Aug 2016 04:31 AM PDT ruby 2.3.1p112 ruby on rails 4.2.6 I run mini test and display error: $ rake test test/integrations/payments_integrations_test.rb rake aborted! NameError: uninitialized constant IntegrationTest This my test: require 'test_helper' class PaymentsIntegrationTest < IntegrationTest fixtures :users before do @client = users(:client) sign_in(@client) @contract = contracts(:contract) end def show_payment_form visit payment_new_path assert page.has_content?('Deposit for contract') end private def sign_in(user) open_session do |sess| sess.post "/sessions", email: user.email, password: user.password sess.follow_redirect! sess.path.must_equal "/" end test_helper.rb ENV["RAILS_ENV"] = "test" require File.expand_path("../../config/environment", __FILE__) require "rails/test_help" require "minitest/rails" # Improved Minitest output (color and progress bar) require "minitest/reporters" Minitest::Reporters.use!( Minitest::Reporters::ProgressReporter.new, ENV, Minitest.backtrace_filter) # To add Capybara feature tests add `gem "minitest-rails-capybara"` # to the test group in the Gemfile and uncomment the following: # require "minitest/rails/capybara" # Uncomment for awesome colorful output # require "minitest/pride" class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all # Add more helper methods to be used by all tests here... end Can you please, explain me what wrong with settings? |
JSON ParseError unexpected token Posted: 18 Aug 2016 04:26 AM PDT I'm trying to consume an API within a big loop. The code is pretty straightforward Video.find_each(:batch_size => 50) do |video| # video_details = HTTParty.get("http://www.domain.com/webmasters/video_by_id?id=#{video.video_id}&thumbsize=medium") video_details = Curl::Easy.perform("http://www.domain.com/webmasters/video_by_id?id=#{video.video_id}&thumbsize=medium") video_data = video_details.body_str video_details = JSON.parse( video_data ) # video.publish_date = video_details['publish_date'] # video.save end it works fine for first 16 iterations, but the it throws this error JSON::ParserError 784: unexpected token at '<html><head><script type="text/javascript"> Any idea why does it happen after 16th call? |
Customize Shrine gem JSON response Posted: 18 Aug 2016 04:08 AM PDT I'm using shrine gem in my rails app for for file uploading. I want to integrate this gem with fineuploader front-end library to enhance the user experience while uploading the files. I'm able to integrate it to an extent that I'm able to upload files through fineuploader front-end via shrine server-side code to my s3 bucket. Now, on a successful upload I receive a 200 status code with JSON response which appear something like following: {"id":"4a4191c6c43f54c0a1eb2cf482fb3543.PNG","storage":"cache","metadata":{"filename":"IMG_0105.PNG","size":114333,"mime_type":"image/png","width":640,"height":1136}} But the fineuploader expects a success property in JSON response with a value of true in order to consider this response successful. So I need to modify this 200 status JSON response to insert this success property. For this, I asked the author of shrine gem and he advised me to use this code in shrine initializer file: class FineUploaderResponse def initialize(app) @app = app end def call(env) status, headers, body = @app.call(env) if status == 200 data = JSON.parse(body[0]) data["success"] = true body[0] = data.to_json end [status, headers, body] end end Shrine::UploadEndpoint.use FineUploaderResponse Unfortunately, this code is not working and infact by using this code fineuploader is throwing following error in console: Error when attempting to parse xhr response text (Unexpected end of JSON input) Please advice me, how I need to modify this code to insert success property with a valid JSON response. |
Voice integration in Ruby on Rails App Posted: 18 Aug 2016 04:29 AM PDT I am new to Ruby on Rails as well as programming. I am trying to develop an application which records a voice and authenticate it the next time. I have tried implementing VoiceIt and this recorder. I made some changes in recorder by converting the plain html to erb. this html to <img id="record" src="img/mic128.png" onclick="toggleRecording(this);"> <a id="save" href="#"><img src="img/save.svg"></a> this erb <%= link_to image_tag("record_audio.png", title: "record", id: "record"), id: "record", :onclick => "toggleRecording(this);" %> <%= link_to image_tag("save_audio.png", title: "save", id: "save"), id: "save" %> But the recorder is not working. Javascript is not called. Please have a look at the recorder link for complete code. This can see Routing error in server. Started GET "/voiceits/recorder.js" for 192.168.1.102 at 2016-08-18 16:52:59 +0530 Started GET "/voiceits/main.js" for 192.168.1.102 at 2016-08-18 16:52:59 +0530 actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:53:in call' Cannot render console from 192.168.1.102! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 Cannot render console from 192.168.1.102! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 web-console (3.3.1) lib/web_console/middleware.rb:131:in call_app' web-console (3.3.1) lib/web_console/middleware.rb:20:in block in call' ActionController::RoutingError (No route matches [GET] "/voiceits/recorder.js"): ActionController::RoutingError (No route matches [GET] "/voiceits/main.js"): web-console (3.3.1) lib/web_console/middleware.rb:18:in catch' web-console (3.3.1) lib/web_console/middleware.rb:18:in `call' I don't know what is happening behind. please help. Thanks in advance. |
Whitespace error on csv file Posted: 18 Aug 2016 03:47 AM PDT task priceupdate: :environment do csvtoopen = open('http://www.someurlhere.com/feed.csv') csv = CSV.foreach(csvtoopen, :headers=>true) csv.each do |row| #Stuff to do with rows here end end Above is my rake task for the csv file, When i try and run this i get this error CSV::MalformedCSVError: Illegal quoting in line 1. My work around was this method. csv = CSV.parse(csvtoopen, :headers=>true, quote_char: "\x00") I'm under the impression it moves things ot a new cell on commas? The issue is i have events coming back with commas. So is there another work around? Heres the csv file http://api.viagogo.net/feeds/ukeventfeed.csv Sam |
No comments:
Post a Comment