Saturday, July 2, 2016

Rails ancestry form outside new | Fixed issues

Rails ancestry form outside new | Fixed issues


Rails ancestry form outside new

Posted: 02 Jul 2016 07:04 AM PDT

I am working on adding nested comments with ancestry, and In Rails cast they created new for with:

def new    @message = Message.new(:parent_id => params[:parent_id])  end  

In controller and simple form with the addition of: <%= f.hidden_field :parent_id %>.

Trying to achive this result outside of new action (home method) I added form this way:

 <%= form_for [current_user, post, Comment.new(parent_id: comment.id)], html: { multipart: true }, remote: true do |f| %>  

But I have a feeling this is not a way it should be (but it works). Do You have any suggestions or is it ok the way it is?

Delaying the toggling action of show/hide until the search is in progress using javascript in rails application

Posted: 02 Jul 2016 07:25 AM PDT

I would like to wait for javascript hide function until my searches are done so that I could make further searches from thereon.

Whenever I make a search then if I press enter, all of sudden my search bar is in hidden state.

For better visualization and understanding, just follow the screen-shot as below;

screenshot.png

index.html.erb

<a href="#" class="toggle-formed" style="float: right;" >Search</a>                    <div id="sample" class="<%= @xvaziris_data.present? ? 'hidden' : '' %>">                        <%= form_tag xvaziris_path, method: 'get', class: "form-group", role: "search" do %>                      <p>                          <center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", class: "form-control-search" %>                              <%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>                          </p>                          <% end %><br>                            <% if @xvaziris.empty? %>                            <center><p><em>No results found for.</em></p></center>                                          <% end %>                        </div>  

search.js

$(document).on('page:change', function () {          $("div#sample").hide();        //    | === HERE      $("a.toggle-formed").click(function(event) {          event.preventDefault();          $("div#sample").fadeToggle();      });  });  

general.scss

.hidden {    display: none;  }  

Any suggestions are most welcome.

Thank you in advance.

undefined method `gsub' for nil:NilClass after installing gems

Posted: 02 Jul 2016 07:42 AM PDT

After installing some gems and deleting them from my gem file, I got this error

undefined method `gsub' for nil:NilClass    Extracted source (around line #16):          <%= link_to (image_tag post.image.url(:medium)), post %>  

I have everything in my app exactly the same as before adding the gems, etc. But still I receive this error. What can I do?

Rails Serializer not returning valid JSON (keys not returned in quotes)

Posted: 02 Jul 2016 06:40 AM PDT

Am having some trouble with a Rails Serializer in an API only app. The app is returning a javascript object where the keys are not enclosed in double quotation marks. Of note, the source API is returning a javascript object with keys not surrounded by quotes.

I've found two posts that seem to be related. The second answer here notes that if you receive an object that's not a string, you don't need to parse it, so I guess that's what's going on here, but I can't figure out what to use in place of JSON.parse response in my model. Another related post here; as suggested there, I've tried return JSON(response) instead of JSON.parse response, which also did not produce valid JSON. I see I can remove the each_serializer: KoboApiSerializer line in my Controller, and have tried doing that with the `return JSON(response) line in the Model.

Any suggestions on what I should do to produce a valid JSON result would be appreciated.

Model, Controller, returned JSON, and source JSON returned from API below. I also have included what is puts'd out to my terminal via the line in my controller. Thanks in advance.

Model:

class KoboApi < ActiveRecord::Base      require 'rest_client'      USERNAME = ENV['KOBO_API_USER']      PASSWORD = ENV['KOBO_API_PWD']      SURVEY = ENV['KOBO_API_SURVEY']      API_BASE_URL = ENV['API_BASE_URL']      def self.get_api_info          uri = "#{API_BASE_URL}/data/#{SURVEY}?format=json"          rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)          response = rest_resource.get          JSON.parse response      end  end  

Controller:

class KoboDataController < ApplicationController      def index          @kobo_info = KoboApi.get_api_info          puts "@kobo_info: #{@kobo_info.inspect}" #values for this returned below.  this shows keys surround with quotes.          @kobo_info.each do |kobo_info|             #some records have NULL for the month_and_year date field.  this if then statement              date = if kobo_info['month_and_year']                  Date.parse(kobo_info['month_and_year'])             else                  nil             end              KoboApi.where(lemurs_quantity: kobo_info['lemurs_quantity'], month_and_year: date, lemur_category: kobo_info['lemur_category'], location_admin1: kobo_info['location_admin1'], location_admin2: kobo_info['location_admin2']).first_or_create          end      render(        json.KoboApi.all,        each_serializer: KoboApiSerializer      )      end  end  

example of object returned from my Rails API app

A serializer is in place (here "kobo_data"), so objects are grouped under that. Am including an example object from those returned - note that the object here doesn't necessarily match those I've posted from source API or from console - am including it to show that keys are not enclosed in quotations.

{      kobo_data: [          {              lemurs_quantity: 20,              month_and_year: "2016-03-01",              lemur_category: "indri",              location_admin1: "toliara",              location_admin2: "androy"          }      ]  }  

example of source json from API:

One object (of the many) returned from the source API. Values here don't match values those above or below - am just including to show that keys are not enclosed in double quotations.

[      {          location_admin1: "fianarantsoa",          location_admin2: "atsimo-atsinanana",          lemurs_quantity: "5",          month_and_year: "2016-01-01",          lemur_category: "brown_lemur",      },  ]  

Putsing it to the terminal....

Values puts'ed out to my terminal via the line in my controller show that it appears to be a valid JSON object, with keys in quotations. As above, the values here do not match the values from my source data - this is just to show that returned values here are enclosed in quotations.

Processing by KoboDataController#index as HTML  @kobo_info: [{"location_admin1"=>"fianarantsoa", "location_admin2"=>"atsimo-atsinanana","lemurs_quantity"=>"5", "month_and_year"=>"2016-01-01","lemur_category"=>"brown_lemur"}    KoboApi Load (0.3ms)  SELECT  "kobo_apis".* FROM "kobo_apis" WHERE "kobo_apis"."lemurs_quantity" = $1 AND "kobo_apis"."month_and_year" = $2 AND "kobo_apis"."lemur_category" = $3 AND "kobo_apis"."location_admin1" = $4 AND "kobo_apis"."location_admin2" = $5  ORDER BY "kobo_apis"."id" ASC LIMIT 1  [["lemurs_quantity", 5], ["month_and_year", "2016-01-01"], ["lemur_category", "brown_lemur"], ["location_admin1", "fianarantsoa"], ["location_admin2", "atsimo-atsinanana"]]  

Finding Post which don't belong to Author in Rails

Posted: 02 Jul 2016 06:33 AM PDT

Suppose I have a Post Model like this:

class Post < ActiveRecord::Base    belongs_to :user  end  

And the User model looks like this

class User < ActiveRecord::Base    has_many :posts, dependent: :destroy      # I have used devise gem for User management    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable,            :validatable, :authentication_keys => [:login]  end  

Then Lets Say X and Y And Z created a Post using their accounts. If X is logged in I can clearly show his Post in Views by just doing this:

current_user.post  

But for some reason I also want the post which don't belongs to X or lets say arbitrary user?? Is there some way where i can take current_user object and pass some method or something like that??

I simply mean i want to get a post except than a particular user or for example current_user (user who is logged in) Thanks

Calling REST APIs without blocking, from Rails application

Posted: 02 Jul 2016 05:37 AM PDT

I have integrated EventMachine with my Rails application, primarily to use ruby amqp for loosely-coupled interactions between services. But now I figure that I need to make some REST API calls in the context of message callbacks and these cannot be blocking either.

I set up EventMachine event loop in a separate thread, and create my AMQP exchanges / queues within it, in a script placed under config/initializers based on this post.

But how do I call REST APIs using em-http-request libraries from all over the application - because I cannot add them in EM's run block.

How to prevent duplicate records being created, but all other before_create methods to run?

Posted: 02 Jul 2016 07:06 AM PDT

A Rails app has an Event and Vote model. Events should be unique.

If a User attempts to create an Event that already exists, save should be prevented, and instead a Vote should be created for the existing Event.

I can prevent the Event from being saved using a custom validation or a before_create action. However, this also prevents the create_vote_on_existing_event method from being run.

Is there a way to selectively run methods when before_create returns false?

My models look something like this

class Event    has_many :votes    before_create :check_event_is_unique  private    def check_event_is_unique      if Event.where( attributes_to_match).any?        errors.add(:base, :duplicate)        create_vote_on_existing_event        return false      end    end      def create_vote_on_existing_event      event = Event.where( attributes_to_match).last      self.user.vote_on event     end  end  class Vote    belongs_to :event  end  

How to invalidate all sessions after user log out in Rails?

Posted: 02 Jul 2016 03:51 AM PDT

I am new to Rails and I am following Michael Hartl's Rails Tutorial, so my code is mostly borrowed from there. Here is the scenario:

I log onto my site using Computer A. Then I log onto the site using the same user id using Computer B. When I log out of the site using Computer A, Computer B remains logged in and can still perform actions. For security reasons, I would like Computer B to be forced to login again when Computer A has logged out. Is there an easy way to invalidate all sessions for a given user upon log out? If you have some sample code that would be very much appreciated.

I also read that it is best practice to use reset_session on log out. However, I had trouble determining whether you should use reset_session before or after logging out the user?

This is from my Sessions Controller:

  def destroy        log_out if logged_in?         # Reset session to prevent session fixation vulnerability      reset_session        flash[:info] = "You are now logged out"      redirect_to root_url    end  

This is from my Sessions Helper:

  # Forgets a persistent session    def forget(user)      user.forget      cookies.delete(:user_id)      cookies.delete(:remember_token)    end      # Logs out the current user    def log_out      forget(current_user)      session.delete(:user_id)      @current_user = nil    end  

Creating custom getters and setters dynamically under STI in Rails

Posted: 02 Jul 2016 03:07 AM PDT

I am relatively new to meta programming and I am trying to define getters and setters in children models under a single table inheritance, like so:

# app/models/player.rb  class Player < ActiveRecord::Base    serialize :equipments      protected    # Define getters for setters for individual sports    def attr_equipments(*attributes)      attributes.each do |attribute|        define_singleton_method(attribute) do          self.equipments[attribute.to_sym]        end          define_singleton_method("#{attribute}=") do |value|          self.equipments[attribute.to_sym] = value        end      end    end  end    # app/models/baseball_player.rb  class BaseballPlayer < Player    after_initialize do      attr_equipments :bat, :glove    end  end  

On a higher layer I would like to do something like this:

# app/controllers/baseball_players_controller.rb  class BaseballPlayersController < ApplicationController    def new      @baseball_player = BaseballPlayer    end  end    # app/views/baseball_players/new.html.haml  =form_for(@baseball_player) do |f|    =f.text_field :bat    =f.text_field :glove    =f.submit   

But with the example above I cannot get or set the attributes even from the console.

> p = BaseballPlayer.new  > p.bat  > # returns NoMethodError: undefined method `[]' for nil:NilClass    > p = BaseballPlayer.new  > p.bat = "Awesome bat"  > # returns ArgumentError: wrong number of arguments (0 for 2..3)  

Could someone help me find the right direction? Many thanks in advance.

Rails_admin dont work in production

Posted: 02 Jul 2016 03:01 AM PDT

I got some problems with my rails_admin gem in the production when I trying make first user admin in Rails console. In the development all works fine. Look at the error and code.

Error terminal:

2.3.0 :001 > u = User.first  ActiveRecord::NoDatabaseError: FATAL:  database "myApp_development" does not exist  

database.production.yml

default: &default    adapter: postgresql    encoding: UTF-8    pool: 5    development:    <<: *default    database: myApp_development    username: deployer    password: password    test:    <<: *default    database: myApp_test    username: deployer    password: password    production:    <<: *default    database: myApp_production    username: deployer    password: password  

use multiple form in a view. which is post to the different action with ajax

Posted: 02 Jul 2016 07:10 AM PDT

Getting trouble with known at the title.

I have two forms in new.html.erb view. One is form_for, other one is form_tag, both as partials.

form_for is to save some data to models.

form_tag is to do little action with params. and give back the processed data to partilal(js). here I'm stuck. this not working.

form_tag is not working. after submitting, the action "urlchanger" don't reflect any data to partial "urlchanged". in My plan, this should get @url, but get errors (detail below).

This is the error respowned by submitting form_tag.

ActionController::RoutingError: No route matches [POST] "/notes/new"  ..  Processing by Rambulance::ExceptionsApp#not_found as JS  Parameters: {"utf8"=>"✓", "url"=>"<iframe src=\"http://hogehoge.com/hoge" frameborder=0 width=510 height=400 scrolling=no></iframe>", "urlchanger"=>"変換"}  Rendered errors/not_found.json.jbuilder (0.2ms)  Completed 404 Not Found in 66ms (Views: 48.1ms | ActiveRecord: 0.0ms)  

as the non partial. everything works fine. but, I want them to work in single view.

notes  --new.html.erb  ----_form.html.erb  ----_urlchanger.html.erb  ----_urlchanged.js  ----_urlchanger.js.erb    !-------------notes/new.html.erb-------------!  <%= render 'form' %>  <%= render 'urlchanger' %>    !-------------notes/_urlchanger.html.erb-------------!  <%= bootstrap_form_tag(controller: "notes", action: "urlchanger", remote: true ) do |f| %>  <%= f.text_field :url, hide_label: true, :class => "form-control", placeholder: "ペーストエリア" %>  <%= f.submit "変換", data: { disable_with: '送信中'} %>  <div id="urlchanged" >    <%= render "urlchanged" %>  </div>  <% end %>    !-------------notes/_urlchanged.html.erb-------------!  <input type="text" class="form-control" value="<%= @url %>">    !-------------notes/_urlchanger.js.erb-------------!  $('#urlchanged').html('<%= j(render("urlchanged")) %>');    !-------------routes-------------!  resources :notes do  collection do    post :create    post :urlchanger  end  end  !-------------Notes controller-------------!  def urlchanger    url = params[:url]    if /(https?:\/\/\D*\w*)/ =~ url      @url = $&    end  end  

Please help. Thank you.

Implement show/hide functionality using javascript in rails application

Posted: 02 Jul 2016 03:19 AM PDT

Actually, I want to execute javascript code into my rails application.

I created new file that is custom.js in "app/assets/javascripts".

custom.js

$( document ).ready(function() {      $("div#test").hide();      $("a").click(function(event) {          event.preventDefault();          $("div#test").fadeToggle();      });  });  

I also added, //= require custom in application.js file but still the code doesn't hide at the very beginning.

application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require turbolinks  //= require bootstrap-sprockets  //= require nicetitle  //= require custom  

index.html.erb

<a href="#" class="toggle-formed" style="float: right;" >Search</a>                    <div id="sample" class="<%= @xvaziris_data.present? ? 'hidden' : '' %>">                        <%= form_tag xvaziris_path, method: 'get', class: "form-group", role: "search" do %>                      <p>                          <center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", class: "form-control-search" %>                              <%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>                          </p>                          <% end %><br>                            <% if @xvaziris.empty? %>                            <center><p><em>No results found for.</em></p></center>                                          <% end %>                        </div>  

general.scss

.hidden {    display: none;  }  

The above custom.js code, when I place in index.html.erb under javascript script tag it works fine. But I don't want to repeat myself in every other controllers/index as the rails is following DRY principle that is DONOT REPEAT YOURSELF.

search.js

$(document).on('page:change', function () {          $("div#sample").hide();        //    | === HERE      $("a.toggle-formed").click(function(event) {          event.preventDefault();          $("div#sample").fadeToggle();      });  });  

Any suggestions are most welcome.

Thank you in advance.

not getting result from whenever gem (0.9.7) in rails 2.3.5 through localhost:3000

Posted: 02 Jul 2016 01:07 AM PDT

 #my rake task        namespace :send_digest_email do       desc "send digest email"        task :send_digest_email => :environment do                       @sender="govind.shawas20@gmail.com"                       recipient= "govind.mietcse@gmail.com" # recieprnt          @school = School.all              @school.each do |s|              MultiSchool.current_school = School.find s.id              # to send mail               FedenaEmailer::deliver_send_custom_mail(@sender,recipient)                                                       end        end    end  

My schedule.rb file

   every 2.minutes do       rake 'send_digest_email:send_digest_email',      :environment => 'development'    end       every :reboot do        rake 'send_digest_email:send_digest_email',       :environment => 'development'     end  

#run command to start job .the commands are

  1. whenever --update-crontab store         [write] crontab file updated      2. crontab -l       # Begin Whenever generated tasks for: store @reboot /bin/bash -l -c     'cd /home/rank/gvs/new_rank/vendor/plugins/rank_gvs_customization &&     RAILS_ENV=development rake send_digest_email:send_digest_email     --silent'            0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58     * * * * /bin/bash -l -c 'cd /home/rank/gvs/new_rank/vendor/plugins/rank_gvs_customization &&     RAILS_ENV=development rake send_digest_email:send_digest_email     --silent'  

# End Whenever generated tasks for: store

I run to check cron is running or not?

   1.service cron status     cron start/running, process 924  

But i am not getting any mail through cron.

when i did rake -T and run rake task than i got the mail.

How to alter the default "is_invalid error" message in a custom validation

Posted: 02 Jul 2016 02:10 AM PDT

I have added validate method in rails model for custom validation. But after adding this method i am getting "is_invalid" error message. below is my validate method.

     validate :check_quantity_of_offer_bale_insepction          def check_quantity_of_offer_bale_insepction          if self.bales_offered_for_inspection.to_i > self.batch_quantity.to_i            self.errors.add(:batch_quantity) << "Bales offered for inspection should be less than Batch Quantity"            end        end  

I don't know from where "is_invalid" error message is coming from . i want to know how to get rid off this "is_invalid" error message.

Auto redirect when timer ends in rails server side

Posted: 02 Jul 2016 12:39 AM PDT

I am making an online examination web-app in rails and I want the user to redirect to a link when the time finishes to end the test (say 25 minutes after start time).

I have implemented a client side countdown timer using FlipClock.js which automatically redirects to the end test link when the timer reaches zero. I know the user can turn off javascript in their browser, so I wanted a server side solution which does something similar.
I am storing start_time in my database.

Belongs_to presence in Rails 5 not working

Posted: 02 Jul 2016 12:11 AM PDT

To my knowledge, the new default in Rails 5 requires belongs_to associations to be present. I made a model with this association, but the problem is I don't get presence validation error when the associated field is empty. Instead I get a database Null Validation error since I set the _id column not to be null. (PG::NotNullViolation because I use Postgres)

Is this behaviour normal? I mean shouldn't I get the rails error only?

BTW, when I add presence validation for the field, it works as I expected.

How to Deploy rails application using apache2 and apache tomcat server

Posted: 01 Jul 2016 11:04 PM PDT

Hi I am new to ruby on rails and I want to deploy my rails app using web server apache2 and application server tomcat and jruby.I have installed tomcat 8.0.36 and apache2.My application runs on tomcat server IP_ADDRESS:8080.

apache2 folders:

apache2.conf conf-enabled magic mods-enabled sites-available
conf-available envvars mods-available ports.conf sites-enabled

Please suggest me how to connect both these server and deploy.If my idea is wrong then suggest me what are the best way to deploy rails app.

Geocoder near method with model associations

Posted: 02 Jul 2016 03:53 AM PDT

I'm trying to get the near method from geocoder gem working with a model that is associated with another model. I have 2 models restaurants and menus, menus belongs to restaurants. I have a form with a search method in each model, the near method works with my restaurants model

 def self.search_for(params)        restaurants = Restaurant.where(category_id: params[:category].to_i)        restaurants = restaurants.near(params[:location],2) if params[:location].present?        restaurants  end  

I'm searching for a restaurant near the user that sells a dish the user has entered, however the code gives a no method error (undefined method 'restaurants')

def self.search_for_menus(params)        menus=Menu.where("dish LIKE ?", "%#{params[:dish]}%") if params[:dish].present?      menus= menus.restaurants.near(params[:location],2) if params[:location].present?     menus    end  

In my console I am able to do m=Menu.find(11) then m.restaurant which returns that restaurant object and can further do m.restaurant.address which gives the address for geocoder near method to work, so I'm not sure how to go about fixing this.

On/off subscription attribute for rails

Posted: 01 Jul 2016 10:44 PM PDT

I currently have an app that can sign up a new subscriber. When they sign up the user is subscribed for one year, I want to make a way of saying "if the year is up your subscription is now turned off until renewal". I recently added a attribute to subscriber called status and I set it to a string. My thought is that I could make a if/else statement that would condition either on or off for the subscriber but I'm not sure if that's the best idea? My question is - What is the best way to handle a case like this? I'll post some code for clarity.

CONTROLLER:

   class SubscribersController < ApplicationController    helper_method :sort_column, :sort_direction      def index      @search = Subscriber.search(params[:q])      @subscriber = @search.result      @search.build_condition if @search.conditions.empty?      @search.build_sort if @search.sorts.empty?    end      def new      @subscriber = Subscriber.new    end      def create      @subscriber = Subscriber.create(subscriber_params)      if @subscriber.save        flash[:notice] = "Subscriber Has Been Successfully Created"        redirect_to new_subscriber_path(:subscriber)      else        render "new"      end    end  

SCHEMA:

    create_table "subscribers", force: :cascade do |t|      t.string   "first_name"      t.string   "last_name"      t.string   "email"      t.string   "phone_number"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false      t.integer  "visit"      t.integer  "mug_number"      t.string   "status"    end  

As you can see everything is pretty basic. I'm just looking mainly for advice on how to handle this situation. any help would be great thanks!

Create special characters in yaml through Ruby

Posted: 01 Jul 2016 09:25 PM PDT

I'm working on a gem and there I need to create a file like database.yml . I'm creating Yaml file but something not happening good . Below is my code

Key value pairs

    STATUS_VALUES =[                          {                                 'default' => {                                              'defaults' =>                                                  {                                                      'adapter' => 'pasql',                                                      'encoding'=> 'utf8',                                                      'database'=> 'mysql',                                                      'username'=> 'root',                                                      'password'=> nil                                                  }                                              }                          },                          {                              'development' =>                                   {                                      '{{<<}}' => '*default'                                  }                          }                      ]      data = STATUS_VALUES      File.open(file, 'w') { |f| YAML.dump(data.to_yaml, f) }  

My Expected output

  - default: &defaults        adapter: pasql        encoding: utf8        database: mysql        username: root        password:     - development:        <<: *default  

My actual output

 - default:        adapter: pasql        encoding: utf8        database: mysql        username: root        password: ''    - development:        !!str '<<': "*default"  

To be clear I have three differences here

  1. first line i.e default , i want it to be default: &defaults
  2. second password needs to be without any value
  3. last line !!str '<<': "*default" needed to be <<: *default

Any help will be greatly appreciating - Have a good day - thanks

Embed Brightcove video into my HTML UI from Brightcove video URL

Posted: 01 Jul 2016 09:16 PM PDT

I am trying to embed brightcove video into my Rails + AngularJS application. I have video URL. I had tried with following HTML tag, But that won't work for me. Help me to find solution.

Below is my code :

<video width="320" height="240" controls>    <source src="http://brightcove.vo.llnwd.net/e1/uds/pd/57838016001/57838016001_1520916807001_Space-Galaxy.mp4" type="video/mp4">    Your browser does not support the video tag.  </video>  

Error starting Rails server: "unexpected .."

Posted: 01 Jul 2016 09:38 PM PDT

I set up a Rails app on OpenShift and pulled the default code. When I tried running it, I got the following error:

C:/Development/Ruby/lib/ruby/gems/2.3.0/gems/activesupport-4.1.4/lib/active_support/dependencies.rb:241:in `load': C:/HEATH3N/FirstApp/config/initializers/session_store.rb:1: syntax error, unexpected .. (SyntaxError)  ../../.openshift/lib/session_store.rb  

I'm unclear as to what the problem is. I looked at the problematic file and don't see anything wrong. I found other questions on Stack Overflow asking about another problem with the file (the new hash style isn't supported on older Ruby versions) but I'm using Ruby 2.3 (Rails 4.1.4) and my error is different.

require File.join(Rails.root,'lib','openshift_secret_generator.rb')    # Be sure to restart your server when you modify this file.    # Set token based on intialize_secret function (defined in initializers/secret_generator.rb)    Rails.application.config.session_store :cookie_store, :key => initialize_secret(    :session_store,    '_railsapp_session'  )    # Use the database for sessions instead of the cookie-based default,  # which shouldn't be used to store highly confidential information  # (create the session table with "rails generate session_migration")  # RailsApp::Application.config.session_store :active_record_store  

Ruby on Rails, retrieving API key from secrets.yml

Posted: 01 Jul 2016 10:21 PM PDT

Can someone help me understand how to retrieve an API key if I'm storing it into secrets.yml?

If I have some kind of google API key 'yt_key':

secrets.yml

development:    secret_key_base: 390257802398523094820 #some key    yt_key: A423092389042430 #some key    test:    secret_key_base: 43208947502938530298525#some key    yt_key: A423092389042430 #some key    production:    secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>    yt_key: <%= ENV["YT_KEY"] %>  

I'm just following the examples, this is how I would set it up right?

So if I publish this to production, I would save the A423092389042430 in heroku and under YT_KEY, correct?

But in development, would I do it this way to retrieve the data:

in /config/application.rb

Yt.configure do |config|    config.api_key = '<%= ENV["YT_KEY"] %>'  end  

or should this be in the the class:

module Sample    class Application < Rails::Application        Yt.configure do |config|        config.api_key = '<%= ENV["YT_KEY"] %>'      end        config.active_record.raise_in_transactional_callbacks = true    end  end  

Or did I set up the configure wrong?

How to use 'SASS' from html template on a rails app?

Posted: 02 Jul 2016 01:10 AM PDT

I'm trying to install an html template in my rails app, so I moved all the assets on public folder and renamed all the html files in erb.

Everything works fine except that 'sass' is not working, any file from the SASS folder of the html template is not doing their work.

So how can I make use of the SASS files of the html template on my rails app?

Rspec expect not working and getting success

Posted: 02 Jul 2016 04:07 AM PDT

I wrote the following code:

require_relative '../ticket'  describe Ticket do    before do      @ticket = Ticket.new()    end  # context "check_ticket" do  #   it 'check_a_ticket' do  #     @ticket.stub(:gets) {"quit"}  #     expect(@ticket.show_tickets(1)).to be_present  #   end  # end  # context "check_tickets" do  #   it 'check_tickets' do  #     t@icket.stub(:gets) {"menu"}  #     expect(@ticket.ticket_viewer(1)).to be_present  #   end  # end    context "exit" do      it 'check_exit' do        result = @ticket.ticket_viewer("quit")        expect(result).to include("Thanks")      end    end  end  

When I try to execute,

expect(result).to eq("something")  

does not work. The case is passed no matter what the value is in eg("something"). Help please.

Simplest Way to Serve Files - Ruby on Rails

Posted: 01 Jul 2016 10:41 PM PDT

What's the simplest way to serve files in Rails?

By this I mean: I'd like to go to, say, http://myserver.com/assets/arbitraryfile.arbitraryformat and have it just load arbitraryfile.arbitraryformat in the browser, letting the browser decide whether to download it or display it or whatever else. (In particular I plan to make a bookmarklet that invokes a *.js file from the server, which in turn loads a *.css file and downloads a font *.tty file from the same.)

Currently I've got an assets resources routing to an assets#show action, but I'm not at all sure how to code my show.

How to redirect to www.example.com/products from example.com/products in Rails 2.3.3

Posted: 01 Jul 2016 07:54 PM PDT

I have successfully used code to redirect my application from example.com to www.example.com

I use the following:

class ApplicationController < ActionController::Base        before_filter :ensure_domain        APP_DOMAIN = "www.example.com"    NAKED_DOMAIN = "example.com"  protected       def ensure_domain      if request.env['HTTP_HOST'] == NAKED_DOMAIN && RAILS_ENV =='production'        #HTTP 301 is a permanent redirect          redirect_to "http://#{APP_DOMAIN}", :status => 301      end    end  

This works fine for links that go to the home page.

However I just realized that if I have a the following url:

example.com/products

The user gets redirected to the home page at www.example.com and NOT www.example.com/products

How can I redirect to the URL the user is trying to access but the www.example.com root and not the example.com root.

In other words if a user wants the following:

example.com/products

I send them to

www.example.com/products

Thanks for any assistance.

I am hosted on Heroku. I am using Zerigo DNS. When I tried using the DNS to forward all traffic from the naked domain to the www.example.com domain the URL still shows the naked domain.

So that did not work.

Rails 4 - Pundit - policies not working

Posted: 01 Jul 2016 08:09 PM PDT

I'm trying to figure out how to use Pundit in my Rails 4 app.

I have a project model, with a projects controller that has a new action in it:

def new  # a bunch of stuff in the new action that I don't think is very relevant here    end  

I then have a project policy in my policies folder that has:

def new?          false          # create?      end        def create?          false        end  

I expect that I should not be able to type url/projects/new in my website because the policy shouldn't allow it. But, I can, and the form renders and I can save it.

Does anyone see what I've done wrong in setting this up?

why do i get a NoMethodError in Devise::RegistrationsController#create in ActionMailer?

Posted: 01 Jul 2016 06:28 PM PDT

I've set up my config to use Mailtrap on Heroku and can confirm that I've got the bulk of it set up. Meaning I receive the emails, but only so long as I don't call methods on the user model. Personalizing the emails with @user.name and automating the user it sends to with @user.email results in a no method error. I thought maybe it had something to do with the fact that I'm sending emails from the user model instead of my customized devise users controller, so I added a create method to that. Which did nothing. The error says undefined method 'email' for nil:NilClass

In my user model I have

class User < ActiveRecord::Base   after_create :new_user   validates :email, presence: true, uniqueness: true, if: -> { self.email.present? }     private      def new_user        UserMailer.new_user(@user).deliver_now      end  end  

In my user mailer I have

class UserMailer < ApplicationMailer        def new_user(user)          @user = user          mail(to: @user.email, subject: 'You will be notified when your account is activated.')      end  end  

And then in my users controller, which is extended from Devise::RegistrationsController, I have

class UsersController < Devise::RegistrationsController   def create    @user = User.new(sign_up_params)   end     private      def sign_up_params          params.require(:user).permit(:firstname, :lastname, :email, :password, :password_confirmation, :approved)      end  end  

Any idea?

How to create a offer strip on top of the navbar of the website which can be minimized?

Posted: 02 Jul 2016 04:46 AM PDT

I saw this offer on a website which was being displayed above the navbar. enter image description here

It looked like this once clicked on the arrow on the top right corner. enter image description here

And how can I make it responsive?

enter image description here

Can anyone share how to implement such a solution? Are there any already existing solutions which I can reuse?

No comments:

Post a Comment