Sunday, May 29, 2016

Rabl if condition not working | Fixed issues

Rabl if condition not working | Fixed issues


Rabl if condition not working

Posted: 29 May 2016 06:58 AM PDT

I'm trying to make a if condition on my rabl file that looks like the following:

node(:profile) do |user|    if user.profile.nil?      ""    else      if Rails.env == "development"        "https://localhost:3000" + user.profile.preview.url      else        user.profile.preview.url       end    end  end  

However I still get the error:

no implicit conversion of nil into String    Extracted source (around line #9):   7  else   8    if Rails.env == "development"   9      "https://localhost:3000" + user.profile.preview.url  10    else  11      user.profile.preview.url   12    end    Rails.root: /home/ubuntu/workspace  

What am I doing wrong?

foundation-rails 6.2.1.0: Can't get JS components to work

Posted: 29 May 2016 06:44 AM PDT

I've been struggling with this for a whole day.

I did the following:

  • Started a fresh Rails app, Rails v.4.2.5
  • Installed the foundation-rails gem, v.6.2.1.0
  • Followed the instructions on https://github.com/zurb/foundation-rails, and made sure application.scss, application.js, and application.html.erb have the required lines.

When I add Foundation css elements like buttons, talbes etc, it works fine, but none of the JS stuff slike tabs, top-menus work. They just render as plain HTML bullet lists and paragraphs.

I'm new to Foundation, and fairly new to Rails as well, so I'm not sure how to troubleshoot this. I really hope someone can help. Thanks! :-)

Rails API Does not split Json

Posted: 29 May 2016 06:53 AM PDT

Weird problem. If the class at the bottom was a module, split the Json without problems, if it was only methods, also works, but the problem is.. when it is a class, it does nos split the Json anymore, returns an empty array.. however, if being a class I do a puts in the class to check the object, it actually puts the object.. Any thoughts about why? How can I fix it?

I have this controller:

 def index     begin       call_employee_work_locations_api        rescue => ex        render :json => {"service unavailable": "0001" }, :status => :service_unavailable     end    end  

I have this service:

def call_employee_work_locations_api     auth = {:username=>ENV["USERNAME"], :password=>ENV["PASSWORD"]}     employee_locations = HTTParty.get(employee_work_Location_url , :basic_auth => auth)     #serialize_work_location(employee_locations)      serializer = EmployeeSerializer.new     serializer.serialize_work_location(employee_locations)  end   

I have this builder:

json.array!(@top_locations) do |location|     json.extract! location, :name, :description, :latitude, :longitude  end  

I have this class:

class EmployeeSerializer        def serialize_work_location(employee_locations)          employee_locations= JSON.parse(employee_locations)          locations=[]            employee_locations["work_locations"].each do |attributes|             location = Location.new(attributes["latitude"],attributes["longitude"],attributes["description"],attributes["name"])            locations.push(location)          end          employee_locations_selector(locations)      end         def top_office_location_selector(locations, city)          top_locations=[]          locations.each do |office|              if office.name == city[0] then top_locations.push(office) end              if office.name == city[1] then top_locations.push(office) end          end          @top_locations = top_locations          p @top_locations <--- it prints the object perfectly, but does not pass to the view, I get an empty array instead.       end         def employee_locations_selector(locations)          city = locations.each_with_object(Hash.new(0)) { |locations, counts| counts[locations.name] += 1 }.max_by{|k,v| v}          top_office_location_selector(locations, city)       end  end  

add variants to a standard set of products and link to back to merchants

Posted: 29 May 2016 06:30 AM PDT

I am trying to achieve upon creation of a merchant that a standard predefined list of products will be allocated to this merchant, along with variants. Each product has a set of properties i.e. Size, Flavour, and each variant would have an option for these properties i.e. for Size it might be Small, Medium, Large. I seem to be able to create all the products with variants though these aren't linked to merchant, and I can't work out how properties for either the product or variants through. I guess in a way this setup is similar to http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast

I am aiming for something like this

enter image description here

add variants after creation method

def add_variants      @product = Product.all        @product.each do |product|          @merchant = Merchant.variant.create!(product_id: product.id, sku: SecureRandom.hex(6), price: 3)        end    end  

merchant model

has_many :variant_merchants    has_many :variants, through: :variant_merchants, dependent: :destroy    has_many :products, through: :variants, dependent: :destroy  

product model

has_many :product_properties    has_many :properties,         through: :product_properties      has_many :variants, dependent: :destroy  

variant model

has_many :variant_merchants, dependent: :destroy    has_many :merchants, through: :variant_merchants      has_many :variant_properties    has_many :properties,        through: :variant_properties      belongs_to :product  

properties model

has_many :product_properties    has_many :products,          :through => :product_properties      has_many :variant_properties    has_many :variants,          :through => :variant_properties  

;; Warning: Message parser reports malformed message packet

Posted: 29 May 2016 06:30 AM PDT

I wanted to create a subdomain api to my server.in in digitalocean for that I did created A record with name api with public ip address.

when I try to test my subdomain terminal with this command host api.myserver.in then I get this error

api.myserver.in has address 218.93.250.18  ;; Warning: Message parser reports malformed message packet.  myserver.in has SOA record ns27.domaincontrol.com. dns.jomax.net. 2016052301 28800 7200 604800 600  

And also whenever i try to ping to this subdomain url like this

ping api.myserver.in  

then I get this

Request timeout for icmp_seq 0  Request timeout for icmp_seq 1  Request timeout for icmp_seq 2  Request timeout for icmp_seq 3  

Forbidden & Denied Access installing Rails app on Google Cloud Engine, Bitnami Ruby stack

Posted: 29 May 2016 05:59 AM PDT

Upon installing the ruby stack on a g1-small instance I am receiving a "403 Forbidden" error returned by the Apache when viewing the host in a browser. 403 Forbidden Error

The app works correctly on another site, I've given all the appropriate permissions, and I've followed the Bitnami Ruby for Google Cloud Platform Guide very closely and I still am not at all able to get the server to show the page. Continually receiving a Forbidden when viewing the root from the browser and the apache error_log:

[Sun May 29 04:21:26.745837 2016] [autoindex:error] [pid 1662:tid   139834521802496] [client XXX.XXX.XXX.XXX:57399]   AH01276: Cannot serve directory /home/bitnami/vec55-rails/public/:   No matching DirectoryIndex (index.html,index.php) found,   and server-generated directory index forbidden by Options directive  

Also, just noticed I don't see a passenger module in the Apache config. It's been a few years since I had to work on rails apps, but isn't the passenger module still required in an install? or is there something unique you are doing in the install? If I'm just wrong and outdated, though, I offer my apologies. As I look at the error, it doesn't sound like Apache recognizes passenger as it's only given reference to an html or php index.

My VirtualHostconfig is:

<VirtualHost *:80>     ServerName vec5.mydomain.com     DocumentRoot "/home/bitnami/vec5-rails/public/"      <Directory "/home/bitnami/vec5-rails/public/">          Options -MultiViews          <IfVersion < 2.3 >          Order allow,deny          Allow from all          </IfVersion>          <IfVersion >= 2.3>          Require all granted          </IfVersion>          RailsEnv development          PassengerEnabled on          PassengerAppRoot "/home/bitnami/vec5-rails/"      </Directory>  </VirtualHost>  

And I've also chown'ed the Apache2 htdocs, and the /home/bitnami/vec5-rails directory for the bitnami.daemon account.

If any Bitnami developers are out the please chime in. For similar questions like this and this Bitnami devs have referenced this older Bitnami Ruby Stack wiki guide and this seemingly more recent Bitnami Custom Ruby on Rails application, respectively, but I'm not sure if the developers have recently tried their Ruby build instructions I mentioned at the start of this question since Google Cloud has updated everything.

Download image files w/URL for rails

Posted: 29 May 2016 05:21 AM PDT

I'm developing a learning application for a nonprofit using rails that WILL NOT have access to the internet. All assets must be housed locally. The application contains thousands of images, which are actually just URLs. I'm rather new to the dev world but have found it very difficult to find a solution to this problem.

A majority of the database content is seeded using a custom rake and cron task. We're using the Dribbble API to pull in most of this content, including the images. Looking at the urls, it looks like Dribbble is using S3 to house their images. Perhaps that is part of the solution. (example url: https://d13yacurqjgara.cloudfront.net/users/4521/screenshots/2742352/nest_notifications.jpg).

I know this topic must be easy for someone out there, but I literally have no experience or success finding a solution. Help and suggestions would be greatly appreciated!

difficulty implementing image zoom for CDN image assets.

Posted: 29 May 2016 04:48 AM PDT

I am having a bit of bother trying to implement image zoom on CDN image assets in my rails e-commerce application.

As you can see from the image and code below. I have the image assets in my index page being brought into the application through a CDN.

These images in turn have a transparent image overlay which appears on hover with further product details.

I would like to configure this so that when the user clicks on the image overlay of the product, image zoom appears on the product that is sitting behind the overlay .

I have tried several methods without success.

How can I achieve this.

enter image description here

index.html.erb

    <body>    <section class='shop'>        <div class="product" style="background-image: url(http://cdn.shopify.com/s/files/1/0051/4802/products/white-mug-1_1024x1024.jpg);">        <div class ="placenta">Snail Bee Mask</div><span><div class="button"><a class="addtocart"><div class="add">Add to Cart></div><div class="added">Added!</div></a></div></span>        <p>The mug you've been dreaming about. One sip from this ceramic 16oz fluid delivery system and you'll never go back to red cups. His slug was massive and he said that the creame would preserve the coupon from all environmental</p>      </div>        <div class="product" style="background-image: url(http://cdn.shopify.com/s/files/1/0051/4802/products/white-mug-1_1024x1024.jpg);">        <div class ="placenta">Snail Bee Mask</div><span><div class="button"><a class="addtocart"><div class="add">Add to Cart></div><div class="added">Added!</div></a></div></span>        <p>The mug you've been dreaming about. One sip from this ceramic 16oz fluid delivery system and you'll never go back to red cups. His slug was massive and he said that the creame would preserve the coupon from all environmental</p>      </div>          <div class="product" style="background-image: url(http://cdn.shopify.com/s/files/1/0051/4802/products/white-mug-1_1024x1024.jpg);">        <div class ="placenta">Snail Bee Mask</div><span><div class="button"><a class="addtocart"><div class="add">Add to Cart></div><div class="added">Added!</div></a></div></span>        <p>The mug you've been dreaming about. One sip from this ceramic 16oz fluid delivery system and you'll never go back to red cups. His slug was massive and he said that the creame would preserve the coupon from all environmental</p>      </div>        <div class="product" style="background-image: url(http://cdn.shopify.com/s/files/1/0051/4802/products/white-mug-1_1024x1024.jpg);">        <div class ="placenta">Jeju Clay Mask</div><span><div class="button"><a class="addtocart"><div class="add">Add to Cart></div><div class="added">Added!</div></a></div></span>        <p>The mug you've been dreaming about. One sip from this ceramic 16oz fluid delivery system and you'll never go back to red cups. His slug was massive and he said that the creame would preserve the coupon from all environmental</p>      </div>        <div class="product" style="background-image: url(http://cdn.shopify.com/s/files/1/0051/4802/products/white-mug-1_1024x1024.jpg);">        <div class ="placenta">Miccosmo aging</div><span><div class="button"><a class="addtocart"><div class="add">Add to Cart></div><div class="added">Added!</div></a></div></span>        <p>The mug you've been dreaming about. One sip from this ceramic 16oz fluid delivery system and you'll never go back to red cups. His slug was massive and he said that the creame would preserve the coupon from all environmental</p>      </div>        <div class="product" style="background-image: url(http://cdn.shopify.com/s/files/1/0051/4802/products/white-mug-1_1024x1024.jpg);">        <div class ="placenta">Placenta Face Wash</div><span><div class="button"><a class="addtocart"><div class="add">Add to Cart></div><div class="added">Added!</div></a></div></span>        <p>The mug you've been dreaming about. One sip from this ceramic 16oz fluid delivery system and you'll never go back to red cups. His slug was massive and he said that the creame would preserve the coupon from all environmental</p>      </div>        </section>          <div class="center">        <%= will_paginate @pins, renderer: BootstrapPagination::Rails %>    </div>      <br>      <!-- JavaScript for zoom functionality) -->      <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>      <script src="js/index.js"></script>      </body>  

javascript

$(document).ready(function(){      $('background-image').zoom();    });  

CSS

.product {    position: relative;    z-index: 1;    float: left;    width: 50%;    height: 300px;    overflow: hidden;    background-position: center center;    background-size: cover;    /* Hide product descriptions */    /* On hover, adds overlay on top of product image */    /* On hover, fade in product descriptions */    /* Styles for each shop item */    /* "Add to Cart" Buttom with 3D transforms and keyframe animation (Works best in Chrome) */  }    .product > * {    margin: 20px 25px;    opacity: 0;    transition: opacity 200ms ease-out;  }    .product:hover:before {    position: absolute;    z-index: -1;    top: 0;    display: inline-block;    width: 100%;    height: 300px;    background: rgba(0, 0, 0, 0.8);    content: "";  }    .product > * {    margin: 20px 25px;    opacity: 0;    transition: opacity 200ms ease-out;  }    .product:hover > *, .product .active {    opacity: 1;  }  

Rails ActiveModel::Serializer nest response in "data": parent

Posted: 29 May 2016 06:14 AM PDT

I have a rails app in which I use the gem active_model_serializers. In my responses I would like to nest my results inside a "data": parent. Currently when I don't get any data for a response I get the following JSON:

[]  

What I want is something like this:

{    "data": []  }  

I would also like to use the same format in cases where I have data, like this:

{    "data": [      {        "id": 135,        [...]  

I've managed to get the structure I want by using render json, like this:

render json: { data: respond_values}  

But in this case my serialiser gets ignored and all the attributes in my model gets returned. My serialiser looks like this:

class TranslationSerializer < ActiveModel::Serializer    attributes :id, :value, :created_at, :updated_at, :language_id    has_one :language    has_one :localized_string, serializer: LocalizedStringParentSerializer  end  

If I instead use respond_with my serialiser works but I don't get the structure I want - the data parent / container is missing.

Any ideas on what I need to to to get my serialiser to work properly?

rails 4 - role based authorization from scratch

Posted: 29 May 2016 04:22 AM PDT

I have recently started learning rails and had to develop an application with three roles: user(admin), student, instructor. I wrote the following code myself. but the problem is that it makes the role of all active users similar to the most recent login. For example, if admin was logged in and later a student logs in and then if admin refreshes her page, she will also become a student. What i should change in my code to fix this problem? And if it is not possible to implement it like this way, suggest me how i should fix this problem. thanks.

here is my users_controller code:

def login  if session[:user_id]!=nil    redirect_to(:action => 'index')  end  end  def attempt_login  if params[:username].present? && params[:password].present?      found_user = User.where(:username => params[:username]).first      if found_user        authorized_user = found_user.authenticate(params[:password])        if authorized_user          flash[:notice] = "Welcome! You are LoggedIn"          session[:user_id] = authorized_user.id          redirect_to(:action => 'index')          return        end      end      found_student = Student.where(:username => params[:username]).first        if found_student          student_id = Student.authenticate( params[:username],params[:password])          if student_id            flash[:notice] = "Welcome! You are LoggedIn"            session[:user_id] = student_id            redirect_to(:action => 'student_index')            return          end        end      found_instructor = Instructor.where(:username => params[:username]).first        if found_instructor          instructor_id = Instructor.authenticate( params[:username],params[:password])          if instructor_id            flash[:notice] = "Welcome! You are LoggedIn"            session[:user_id] = instructor_id            redirect_to(:action => 'instructor_index')            return          end         end      flash[:notice] = "Invalid username/Password combination."      redirect_to(:action => 'login')  end  end      def logout  flash[:notice]="Logged out"  session[:user_id] = nil  redirect_to(:action => "login")  end  

and here is my application_controller.rb code

def require_login    unless session[:user_id] or config.my_config        flash[:notice] = "You are not Logged In"        redirect_to :root        return false    else      return true    end    end  

Changing submit button text value per form

Posted: 29 May 2016 04:21 AM PDT

I'm rendering a form on a few different pages, such as: edit, new, show. Now on the submit button it says: "update post" and "create post". I know that there is a way to add custom text to the buttons <%= f.submit "Text" %>. But because i'm rendering the form it shows that value on each of the pages. So i'm wondering if there is a way where i can add the custom text value per page, without having to copy the whole form itself.

Why do I create a new model object twice in a form?

Posted: 29 May 2016 06:05 AM PDT

Following various parts of the internet, I have the following code:

Controller

class StudiesController < ApplicationController        def new          require_user          @study = Study.new      end        def create          @study = Study.new(study_params)          if @study.save              flash[:success] = "You made it!"              redirect_to root_path          else              flash[:danger] = "Uh oh—something went wrong"              redirect_to study_path          end      end  end  

View

<%= form_for(@study, url: {action: :create}, class: "study-form") do |f| %>      <%= f.text_field :title %><br>      <div class="btn-submit">          <%= f.submit "I studied today!", class: "btn btn-primary margin-top" %>      </div>  <%= end %>  

It works, but my question is: Why do I need Study.new called twice? Why do I call it in create if I've already called it in new?

Rails + Devise: "Reset password token is invalid" message on password reset

Posted: 29 May 2016 03:16 AM PDT

I've been experiencing this weird error on the production version of my rails site for a while now. This does not occur locally, frustrating my debugging efforts.

I have followed the recommendations made in the following SO questions:

Upgrading to devise 3.1 => getting Reset password token is invalid Rails 4 + Devise: Password Reset is always giving a "Token is invalid" error on the production server, but works fine locally.

Specifically, changing my reset_password_instructions.html.erb file to:

<p>Hello <%= @resource.email %>!</p>    <p>Someone has requested a link to change your password. You can do this through the link below.</p>    <p><%= link_to 'Change my password', edit_user_password_url(@resource, :reset_password_token => @token) %></p>    <p>If you didn't request this, please ignore this email.</p>  <p>Your password won't change until you access the link above and create a new one.</p>  

I am using the following gems:

devise (3.5.9)        bcrypt (~> 3.0)        orm_adapter (~> 0.1)        railties (>= 3.2.6, < 5)        responders        thread_safe (~> 0.1)        warden (~> 1.2.3)  

When I create a test user on the production site, then click "forgot my password", it generates a reset token on the server (which I can see as XYZ123 via Rails Console).

If I create, via Rails Console, a token generator (Devise::TokenGenerator.new) with our secret key as per the Devise source, I am able to convert the token in the link (raw) emailed to the user to the reset token stored in the database. These match exactly, and if I use "User.find_or_initialize_with_error_by" in the rails console on production it is able to correctly find the user associated with the token. Of course, I'm doing this all manually following the devise source code so perhaps I'm doing something that the code isn't.

Does anyone have any theory as to why this might happen? In addition, the URLs being generated by my website for the password reset email are like:

http://www.WEBSITE.com/users/password/edit.<USER_ID>?reset_password_token=<CORRECT_RAW_RESET_PASSWORD_TOKEN>?reset_password_token=<CORRECT_RAW_RESET_PASSWORD_TOKEN>  

Not sure why the reset_password_token param is included twice in this - in the email I receive via Gmail it is only included once.

`expected 200` error in Rspec test for `get` API request

Posted: 29 May 2016 05:46 AM PDT

I'm trying to write some rspec tests to check API endpoints for an API-only application.

Testing error

Failure/Error: expect( res ).to be_success         expected 200 to respond to `success?`  

But if the same call (with full api url) is made from another application it works fine and returns a response.

Example from other application:

res = RestClient.get "site.io/api/v1/projects/1"  p JSON.parse(res)  

Blog example I'm trying to follow: (http://matthewlehner.net/rails-api-testing-guidelines/).

# spec/requests/api/v1/messages_spec.rb  describe "Messages API" do    it 'sends a list of messages' do      FactoryGirl.create_list(:message, 10)        get '/api/v1/messages'        json = JSON.parse(response.body)        # test for the 200 status-code      expect(response).to be_success        # check to make sure the right amount of messages are returned      expect(json['messages'].length).to eq(10)    end  end  

My Application

/requests/projects_spec.rb

require 'rails_helper'  RSpec.describe Project do    describe "show_project" do          before do            @project1 = create(:project)        end          it "Checks if responds successfully" do          res = get '/api/v1/projects/1'          expect( res ).to be_success        end    end  end  

/factories/projects.rb

FactoryGirl.define do    factory :project do      name "Thing"      key "123123"    end  end  

routes.rb

namespace :api, :defaults => { :format => 'json'} do      namespace :v1 do        resources :projects, only: [:create, :show]        end      end  end  

I don't have much experience with testing, so if anyone can point me in the correct direction I would really really appreciate it.

can't run both phpmyadmin and rails server on cloud9

Posted: 29 May 2016 02:59 AM PDT

I am working on a rails project on cloud9 and I followed this tutorial to install PhPmyadmin.

The problem is that I can't run at the same time a rails server and a php my admin server since they both seem to use the same Port. To launch my rails server, I use rails s -b $IP -p $PORT.

Here is the error I get:

/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/socket.rb:205:in `bind': Address already in use - bind(2) for 0.0.0.0:8080 (Errno::EADDRINUSE)  

Has anyone an idea how to fix this?

What should I name the user used to deploy my rails app?

Posted: 29 May 2016 02:33 AM PDT

I have an app named my_app. I need to set up a deploy user on my server that can deploy the app (using capistrano, or similar).

What are the guidelines to naming this user? Should I just name it my_app as well? Or should I use www-data as some tutorials suggest? The latter could be shared among multiple apps on the same server.

Wondering if there was any real pro/cons between the options.

Thanks!

Ruby on rails. Sort a hash by number of endorsements to display in a chart

Posted: 29 May 2016 02:35 AM PDT

I've made a statstics page on which i display a chart with users and number of endorsements they have, which looks like this: enter image description here

What I want to do now, is to sort the displayed result by the number of endorsements, and not sure how to properly do that.

The @data I am displaying is built like this:

@data = @users.map { |user|              amount = user.inbound_endorsements.joins(:endorsed_user).group(:name).count                if !amount.empty?                  {name: user.name, data: amount}                end              }  

And in my view,

<%= @data.compact %>  

Gives a hash like this:

[{:name=>"Jess Corwin", :data=>{"Jess Corwin"=>1}}, {:name=>"Rhiannon Nicolas", :data=>{"Rhiannon Nicolas"=>1}}, {:name=>"Assunta Pfeffer", :data=>{"Assunta Pfeffer"=>2}}, {:name=>"Rafaela Farrell", :data=>{"Rafaela Farrell"=>1}}, {:name=>"Maurine Hettinger", :data=>{"Maurine Hettinger"=>1}}]

And I want to sort it by the number.

I've tried diffeerent approaches like:

<%= @data.compact.sort! %>  <%= @data.compact.sort_by{ |name,data| data } %>  <%= @data.compact.sort_by{ |d| d[:data] } %>  

and other similiar approaches, most of them result in an error:

comparison of Hash with Hash failed

Any help on how can I accomplish this will be appreciated!

jQuery click on load page w/ Carrierwave video upload

Posted: 29 May 2016 02:04 AM PDT

how are you doing?

I am facing a technical issue that I'm not sure can be resolved. I'm building a rails web app with which people can upload videos.

The button to upload a video is on the right end of the screen When people click to upload a video, they are redirected to the carrierwave 'simple form for'.

Here they can click on the button 'choose file' to upload a video from their computer or smartphone Here is the code for the simple form:

    <div class="container">    <h1>Create a new review</h1>    <%= simple_form_for(@review) do |f| %>      <%= f.error_notification %>      <fieldset class="form-group">        <%= f.input :video, class: 'form-control' %>        <%= f.input :video_cache, as: :hidden, class: "file required" %>        <%= f.input :place_id, collection: @places, prompt: "Where are you?", class: 'form-control' %>        <%= f.input :mood,            :collection => [[true, 'Nice place!'], [false, 'I won\'t come back...']],            :label_method => :last,            :value_method => :first,            :as => :radio_buttons,            :item_wrapper_class => 'inline',            :checked => true        %>      </fieldset>      <%= f.submit %>    <% end %>  </div>  

My goal is the following: i want to trigger the click on "choose file" immediatly when the page loads: that would reduce friction for the smartphone users, making them only 2 clicks away from uploading a video, instead of 3, and the users would be able to directly upload videos.

I tried many different jQuery 'click' triggers on page load, but none of these seem to work. I'm not sure what the reason is, but maybe it's because the "choose file" is a simple form and not a "real button"?

Any help would be much appreciated ! Thanks a lot guys Have a great day

How do you make POST request with a XML data body using HTTParty on Rails

Posted: 29 May 2016 04:35 AM PDT

I'm currently trying to make an api call to a server which just accepts my data in form of an xml. I tried calling the service from postman and it works like a charm.

curl -v -X POST -H "x-apiKey: 83202136355d1704350fb3ef596ac126" -H "Content-Type: application/xml" -d '<Request LanguageCode="en" emailAddress="your email" mobileNumber="+4477....." gate="212" boardingHHMM="18:40" departHHMM="19:10" arriveHHMM="20:30" ffMiles="" DepartTerminal="Term 2" ffTier="" message="Sample" CabinName="Economy" > <Barcode firstName="Arie" lastName="van der Veek" title="MR" bookingRef="PNR123" depAirportCode="AMS" arrAirportCode="CDG" carrier="XS" flightNumber="56" depDate="2015-06-06" classCode="Y" seatNumber="21B" seqNumber="002" ffAirline="ZZ" ffNumber="123456789" ticketNumber="000123456789012" issuingCarrier="ZZ" /> </Request>' "https://dev2dbp.api.aero/api/ZZ"  

Now I tried to implement this api call in Ruby on Rails using the following code, but sadly I'm getting an ERROR 500 everytime.

class FlightTicketController < ApplicationController    #  get 'flight_ticket/get_ticket'  def get_ticket      response = HTTParty.post(      "https://dev2dbp.api.aero/api/ZZ",      :headers => {"x-apiKey" => "83202136355d1704350fb3ef596ac126","Content-Type" => "application/xml"},      :body => '<Request LanguageCode="en" emailAddress="your email" mobileNumber="+4477....." gate="212" boardingHHMM="18:40" departHHMM="19:10" arriveHHMM="20:30" ffMiles="" DepartTerminal="Term 2" ffTier="" message="Sample" CabinName="Economy" > <Barcode firstName="Arie" lastName="van der Veek" title="MR" bookingRef="PNR123" depAirportCode="AMS" arrAirportCode="CDG" carrier="XS" flightNumber="56" depDate="2015-06-06" classCode="Y" seatNumber="21B" seqNumber="002" ffAirline="ZZ" ffNumber="123456789" ticketNumber="000123456789012" issuingCarrier="ZZ" /> </Request>'   )    render xml: response    end      end  

Do you have any tips to make this work?

Ruby & Mongoid - Uninitialized constant

Posted: 29 May 2016 05:38 AM PDT

I'm getting "uninitialized constant SwimResult error":

class LegResult    include Mongoid::Document    field :secs, type: Float    embedded_in :entrant    embeds_one :event, as: :parent    validates_presence_of :event      after_initialize do |doc|      doc.calc_ave    end        def calc_ave      end      def secs=value        self[:secs] = value      calc_ave      end  end      class SwimResult < LegResult    field :pace_100,  as: :pace_100, type: Float      def calc_ave    end  end        class BikeResult < LegResult    field :mph,  as: :mph, type: Float      def calc_ave    end  end  

I know it can occur when classes are in a separate files, but in my case they're all in one - class LegResult and two subclasses inheriting after it. I'll appreciate any help.

Rails namespacing concerns based on model name

Posted: 29 May 2016 05:30 AM PDT

I am looking to separate concerns for some subset of function specific to a model. I have referenced here and followed this pattern

module ModelName::ConcernName    extend ActiveSupport::Concern      included do      # class macros    end      # instance methods    def some_instance_method      end      module ClassMethods      # class methods here, self included    end  end  

However, when I try to start the server it would result in the following error

Circular dependency detected while autoloading constant ModelName::ConcernName

I am wondering what is the best way to do concerns for some subset functions of a model.

Edit

Providing the model code: path: app/models/rent.rb

Now I have a lot of checking logic in my model

class Rent < ActiveRecord::Base      def pricing_ready?          # check if pricing is ready      end        def photos_ready?          # check if photo is ready      end        def availability_ready?          # check if availability setting is ready      end        def features_ready?          # check if features are set      end  end  

I want to separate it in concern

class Rent < ActiveRecord::Base      include Rent::Readiness  end  

And organise the concern by namespace path: app/models/concerns/rent/readiness.rb

module Rent::Readiness    extend ActiveSupport::Concern      included do      # class macros    end      # instance methods    def pricing_ready?      # check if pricing is ready    end      ...      module ClassMethods      # class methods here, self included    end  end  

Now I got it working if I just do class RentReadiness with the path in app/models/concerns/rent_readiness.rb

Extract All HTML tags from the particular page In Ruby

Posted: 29 May 2016 01:12 AM PDT

I need to extract all HTML tags from a webpage into an array without the data inside the tags using Capybara in Ruby

Rails 'rapidfire' gem, is it possible to set a one chance limit per user for taking the survey/exam?

Posted: 29 May 2016 12:21 AM PDT

I´m trying to do this, but I can´t find out how to:(

I´m creating a simple teachers/students plataform (a teacher creates exams online, a student take the exam(s)).

Everything seems to work with the gem, but the main porpose isn´t working, a student is not supposed to be able to answer a test several times. I´m not a rails expert of course, but I´d like if you´d guide me in the right direction.

My rapidfire questions_groups/index.html.erb has something like these(I think this is the important part)

<%= render partial: "question_group", collection: @question_groups%>  

And my _questions_group.html.erb partial has this:

<tr id= "question_group_<%= question_group.id %>">    <td>      <% if can_administer? %>        <%= link_to question_group.name, question_group_questions_path(question_group) %>       <% else %>        <%= question_group.name %>      <% end %>     </td>  <td>    <ul class="horizontal-list">      <!--######### My problem!!!!-->    <% @answer_groups.each do |answer_group| %>      <%if current_user.id!=answer_group.user_id&&answer_group.question_group_id!=question_group.id%>         <li><%= link_to "Answer Questions", new_question_group_answer_group_path(question_group) %></li>      <%end%>            <%end%>    <!--#########-->      <% if can_administer? %>      <li><%= link_to "Results", [:results, question_group] %></li>      <li><%= link_to "Delete", [question_group], method: :delete %></li>    <% end %>    </ul>   </td>  </tr>  

I thought about a solution, and iterated through that @answer_groups collection in order to know if the user has answered the question_group before, BUT I couldn't because I needed to define the collection, but I wasn´t able to properly pass it together with the @question_groups that is passed when the partial is rendered in the index.

I'd like some help please. Thank you!

Testing Rails Typus Routes

Posted: 29 May 2016 02:03 AM PDT

Should I test routes generated from TYPUS ?

Looking around for a while but can't find a way to test routes that TYPUS generates. I tried the following, the test is passing but it does not make sens to me since whatever controller action I give it's working.

controller_action = Hash[ users: %w(list of actions of User controller),....]    controller_action.each do |controller, actions|      actions.each do |action|        %w(get post patch delete).each do |http_verb|          it 'should get /#{controller}/#{action}' do            assert_routing({ method: http_verb,                             path: "/#{controller}/#{action}/1" },                            { controller: "#{controller}", action: "#{action}", id: '1' })          end        end      end    end    

Thanks for your help

Evaluation - polymorphic associations on feedback loop

Posted: 28 May 2016 11:08 PM PDT

I'm trying to figure out how to implement an evaluation model in my Rails 4 app.

I've previously asked these related questions but am yet to solve this problem:

Rails 4 Polymorphic associations and concerns

Rails 4 - post completion evaluations model - structure

I have:

class Evaluation < ActiveRecord::Base      belongs_to :evaluator, :polymorphic => true    belongs_to :evaluatable, :polymorphic => true  

I have also made concerns for evaluator and evaluatable as:

module Evaluator      extend ActiveSupport::Concern        included do           has_many :given_evaluations, as: :evaluator, dependent: :destroy, class_name: 'Evaluation'        end  end  module Evaluatable      extend ActiveSupport::Concern        included do           has_many :received_evaluations, as: :evaluatable, dependent: :destroy, class_name: 'Evaluation'      end  end  

I have included each concern in my user model:

class User < ActiveRecord::Base     include Evaluator     include Evaluatable  

In my show page, I want to show a particular user's evaluations (received from other users -who are evaluators).

In my show, I have:

<% Evaluation.find(params[:id]).received_evaluations.order('created_at DESC').each do |eval| %>                                  <div id="portfolioFiltering" class="masonry-wrapper row">                                          <%= eval.remark %>                                          <%= eval.personal_score %>                                          <small><%= eval.created_at %></small>  

In my evaluations form, I"m not sure how to designate the recipient of the evaluation. I have made the basic form, but I'm not clear about how to tie it to the user who should receive the evaluation.

<%= simple_form_for(@evaluation) do |f| %>    <%= f.error_notification %>      <div class="form-inputs">      <%= f.input :score, collection: 1..10, autofocus: true, :label => "How do you rate this experience (1 being did not meet expectations - 10 being met all expectations) ?" %>        <%= f.input :remark, as: :text, :label => "Evaluate your project experience", :input_html => {:rows => 10}  %>  

My evaluations table has:

    t.integer  "user_id"      t.integer  "evaluatable_id"      t.string   "evaluatable_type"      t.integer  "overall_score"      t.integer  "project_score"      t.integer  "personal_score"      t.text     "remark"      t.boolean  "work_again?"      t.boolean  "continue_project?"      t.datetime "created_at",        null: false      t.datetime "updated_at",        null: false    end      add_index "evaluations", ["evaluatable_type", "evaluatable_id"], name: "index_evaluations_on_evaluatable_type_and_evaluatable_id", unique: true, using: :btree  

In my users controller, I have:

def show      # authorize! :read, @user      @received_evaluations = @user.received_evaluations    end  

I currently get an error that says:

undefined method `received_evaluations' for #<Evaluation:0x007fb8c4b32160>  

I'm not sure what this message means or how to solve it.

If I change the show to:

<% @user.received_evaluations.each do |eval| %>  

I get this error:

undefined method `received_evaluations' for nil:NilClass  

Blocked a frame with origin "https://cdn.site.ru" from accessing a frame with origin "https://site.ru". Protocols, domains, and ports must match

Posted: 28 May 2016 10:44 PM PDT

I use Ruby on Rails.

There https://site.ru site.

There is also a host address - http://remotesiter.ru. And https://cdn.site.ru, which masks http://remotesiter.ru (CNAME record).

In ApplicationController I wrote this:

before_filter :set_csp  def set_csp      csp = "default-src 'self';"      csp += "script-src 'self' 'unsafe-inline' 'unsafe-eval';"      csp += "style-src 'self' 'unsafe-inline';"      csp += "frame-src 'self' https://www.youtube.com https://cdn.site.ru"        response.headers['Content-Security-Policy'] = csp  end  

With this code I could give access only to YouTube videos, and local scripts and styles.

And the error occurs:

Blocked a frame with origin "https://cdn.site.ru" from accessing a frame with origin "https://site.ru". Protocols, domains, and ports must match.

How to fix it?

Mixed Chart Types using Chartkick/Highcharts on Rails

Posted: 28 May 2016 10:14 PM PDT

I'm trying to create a mixed column/line chart using Highcharts.

I've been trying to use the library functionality to set one of my data series to be of type "line". I have tried a few different approaches, but I can't seem to figure out how to pass the type parameter of a given series using the Highcharts API.

<%= column_chart( ChartData.new(@forecast).revenue_and_net_income, library: {    title: {      text: "Revenue and Net Income"    },    series: [{      1 => {        type: "line"      }    }],  } ) %>   

Where my data come from the following method:

def revenue_and_net_income  data = [    {      name: "Revenue",      data: revenue_by_year    },    {      name: "Net Income",      data: net_income_by_year,    }  ]  

end

Not sure what I'm doing wrong? I only seem to be able to access the Highcharts API methods listed under 'Chart', none of the series options etc. seem to work. Can anyone point me in the right direction for how to successfully get this to work?

Hartl rails tutorial -- current_user.microposts.build

Posted: 28 May 2016 10:19 PM PDT

Not exactly sure how to frame this question. I'm confused as to how current_user.microposts.build works, as shown here:

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

I understand that current_user was defined earlier in the sessions helper, but where does microposts come from? I believe we're accessing the microposts model which is linked to a user with belongs_to, but the model itself is called Micropost -- so how does rails know that Micropost = microposts? In addition, when we use belongs_to, why do we do belongs_to :user instead of belongs_to user?

How to stub a third party object using rspec-mock?

Posted: 28 May 2016 09:47 PM PDT

I'm kinda new to rspec-mock, now I'm integrating hominid to communicate with Mailchimp, I want to stub some method calls, so my request doesn't actually go to Mailchimp. Here is what I'm doing

config/initilizers/mailchimp.rb

MAILCHIMP = Hominid::API.new(ENV['MAILCHIMP_API_KEY'])  LIST_ID   = ENV['MAILCHIMP_LIST_ID']  

user.rb

class User < ActiveRecord::Base    before_create :add_subscription    private      def add_subscription        MAILCHIMP.list_subscribe(LIST_ID, .......) # Some params following      end  end  

So as you see, for every user created, a list_subscribe will be call on MAILCHIMP, now I don't want list_subscribe was actually called in every test because User was used everywhere, so I config globally a stub like this:

spec/spec_helper.rb

RSpec.configure do |config|    config.before(:each) do      allow_any_instance_of(Hominid::API).to receive(:list_subscribe).and_return(true)    end  end  

I expected MAILCHIMP instance doesn't call list_subscribe but just return true, because if list_subscribe was called, some unexpected requests will go to Mailchimp, I want to prevent this. But my above code doesn't work, what I'm wrong? How to fix this?

Moreover, an answer is likely similar to my case here How should I stub a method globally using RSpec?

I appreciate any help & suggestion? Thanks!

local rvm ruby installation and remote rbenv ruby installation - Can they coexist?

Posted: 28 May 2016 09:24 PM PDT

I'm running into an SSHKit::Runner::ExecuteError while trying to push a ruby app from a repo to a remote server.

On

$: bundle exec cap production deploy  

I get

DEBUG [506a96fd] Running [ -d ~/.rvm ] as deploy@168.257.12.345  DEBUG [506a96fd] Command: [ -d ~/.rvm ]  DEBUG [506a96fd] Finished in 1.496 seconds with exit status 1 (failed).  DEBUG [8e553e85] Running [ -d /usr/local/rvm ] as deploy@168.257.12.345  DEBUG [8e553e85] Command: [ -d /usr/local/rvm ]  DEBUG [8e553e85] Finished in 0.074 seconds with exit status 1 (failed).  DEBUG [d6f82812] Running ~/.rvm/bin/rvm version as deploy@168.257.12.345  DEBUG [d6f82812] Command: ~/.rvm/bin/rvm version  DEBUG [d6f82812]    bash: /home/deploy/.rvm/bin/rvm: No such file or directory  (Backtrace restricted to imported tasks)  cap aborted!  SSHKit::Runner::ExecuteError: Exception while executing as deploy@168.257.12.345: rvm exit status: 127  rvm stdout: Nothing written  rvm stderr: bash: /home/deploy/.rvm/bin/rvm: No such file or directory    SSHKit::Command::Failed: rvm exit status: 127  rvm stdout: Nothing written  rvm stderr: bash: /home/deploy/.rvm/bin/rvm: No such file or directory  

After many hours troubleshooting and searching similar error messages on the interweb I came to the question of whether it's common practice to install ruby on my local machine with rvm, and push an app from a repo to a remote machine where ruby is installed with rbenv. My thought was that the "No such file or directory" error meant that my local installation, based on how its installed locally, is looking for an rvm folder on the remote, and when it doesn't find it it complains.

My next step was to install the same ruby version locally, using rbenv, but other research supports that rvm is incompatible with rbenv and you should remove all traces of rvm before using rbenv. Both are installed on my local machine.

Is there a hack to make this work without having to do a blanket uninstall of rvm locally and every gem that's associated with it, or do I manually create the folder on the remote as explained in this answer? Honestly looking for the cleanest, best practice with this. Many thanks in advance.

Gemfile

# Added per gorails.com tutuorial @ gorails.com/deploy/ubunt/14.04  gem 'capistrano', '~> 3.4.0'  gem 'capistrano-bundler', '~> 1.1.2'  gem 'capistrano-rails', '~> 1.1.1'    # Add this if you're using rbenv  # gem 'capistrano-rbenv', github: "capistrano/rbenv"    gem 'capistrano-rvm', github: "capistrano/rvm"  

Capfile

require 'capistrano/setup'  require 'capistrano/deploy'    require 'capistrano/bundler'  require 'capistrano/rails'    require 'capistrano/rvm'    set :rvm_type, :user  set :rvm_ruby_version, '2.0.0-p451'    # Load custom tasks from `lib/capistrano/tasks` if you have any defined  Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }  

config/deploy.rb

lock '3.4.1'  set :application, 'my_app'  set :repo_url, 'https://github.com/my_acct/my_app.git'  set :deploy_to, '/home/deploy/#{my_app}'    namespace :deploy do    after :restart, :clear_cache do      on roles(:web), in: :groups, limit: 3, wait: 10 do      end    end  end  

config/deploy/production.rb

set :stage, :production  server '168.257.12.345', user: 'deploy', roles: %w{web app}  

versions

ruby 2.3.1 (local and remote)  rbenv version 2.1.5  rvm 1.27.0  

No comments:

Post a Comment