Wednesday, August 31, 2016

Heroku: Sendgrid add-on with custom domain | Fixed issues

Heroku: Sendgrid add-on with custom domain | Fixed issues


Heroku: Sendgrid add-on with custom domain

Posted: 31 Aug 2016 08:19 AM PDT

I'm trying to set up the Heroku Sengrid plugin for a custom domain. I need it because we have ssl certificate on the custom domain, not on the basic .herokuapp.com.

The feature: reset your password email from devise.

In my config/environments/production.rb, I have this line:

config.action_mailer.default_url_options = { :host => ENV['MAILER_URL'] }

When the MAILER_URL variable is set to basic_domain.herokuapp.com, I can send an email for resetting a password. But the links in it will lead to the scary page 'this site is not secure, are you sure?'.

I can also set the MAILER_URL variable to great_custom_domain.com, which has an ssl certificate. But the email will never be send, and in my server log I can read :

Net::SMTPAuthenticationError (451 Authentication failed: Could not authenticate).

After reading other answers, I double checked the Sendgrid credentials.

Activeadmin: Filtering in index do

Posted: 31 Aug 2016 08:07 AM PDT

I am learning about activeadmin. I want that a column in my "index do" of my site display only certain values rather all. For example in my site there is a column score. This column shows the following values

11 10 5 6 7

then I need to know what method to use in the next lines

index do     column : score  end do  

to show only the values greater then 8. I am trying

index do     column : score > 8  end do  

but this does not work

Template is missing - Rails

Posted: 31 Aug 2016 08:20 AM PDT

i'm gotting this error from my web page, when i try to go to "localhost:3000/suscribir" i got this error:

Missing template subscribe/create, application/create with {:locale=>[:es, :en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}.  

this is my routes.rb file...

  post '/suscribir' => 'subscribe#create'    mount Refinery::Core::Engine, at: Refinery::Core.mounted_path  

this is the subscribe controller...

class SubscribeController < ApplicationController    def create      logger.info "suscripcion #{params.inspect}"      user = user_params(params)      MailchimpWrapper.subscribe(user, params[:group_name], params[:group])      redirect_to '/gracias'    rescue Mailchimp::Error => e      logger.error "ERROR mailchimp #{e.message} #{params.inspect}"    end      private      def user_params(params)      user = {        email: params[:email].try(:downcase),        first_name: params[:first_name].try(:titleize),        last_name: params[:last_name].try(:titleize),        city: params[:city].try(:titleize),        phone: params[:phone],        comment: params[:comment].try(:titleize)      }      user    end  end  

You can check the line "redirect_to '/gracias'"

and this is the gracias.html.erb :

<section class="container thanks-subscribe">    <span>Gracias por suscribirte!</span>    <p>Si es la primera vez que te registras a nuestra lista de contactos, revisa tu correo. Te estaremos enviando un correo de confirmación</p>    <a href="/home"><button>Regresa a la página principal y sigue navegando</button></a>  </section>  

without rescue from mailchimp i got this error..

SyntaxError in SubscribeController#create  C:/Sites/ifurniture/app/controllers/subscribe_controller.rb:22: syntax error, unexpected end-of-input, expecting keyword_end  

i'll be watching for your help, thanks.

rails: add row to fixed header table using ajax

Posted: 31 Aug 2016 07:34 AM PDT

I have a fixed header table that scrolls the rows when they pass the fixed height. I'm adding new rows via ajax. But if I add a new one and the rows are below the max height, the new row won't appear. If its after the max height the table previous table shrinks and the new row appears at the end.

this is my ajax call:

$('.table_meetings').append(" <%= j render partial: 'projects/new_overview_partials/meeting', locals: {dd: @issue} %>");  

and this is my table:

<table class="table_meetings scroll">    <thead class="header">        <tr class="myspan1 title">            <th style="width: 39.5%; padding-left: 10px">Name</th>        </tr>  </thead>        <tbody >          <% @total.each do |dd| %>              <%= render partial: 'projects/new/rows', locals: {dd: dd} %>            <% end %>        </tbody>      </table>  

css:

.table_meetings{      border-collapse:collapse;      width: 100%;      font-size: 11pt;    }      .table_meetings th {      font-size: 11pt;      text-align: left;      padding-top: 10px;      padding-bottom: 10px;    }      .table_meetings tr p{      padding-bottom: 5px;      margin-bottom: 0px;    }    .table_meetings tr a{      font-size: 11pt !important;    }      .table_meetings td{      padding-top: 10px;      padding-bottom: 10px;      border-bottom: 5px solid white;      height: 40px;    }      table.scroll {      width: 100%;       border-spacing: 0;    }      table.scroll tbody { display: block; }    table.scroll thead { display: inherit; }      thead tr th {      height: 30px;      line-height: 30px;    }      table.scroll tbody {      height: 700px;      overflow-y: auto;      overflow-x: hidden;    }  

Combining scopes doesn't work

Posted: 31 Aug 2016 07:33 AM PDT

I'm trying to combine three scopes in one (one scope uses the other two).

I want to get all videos which don't have certain categories and certain tags.

Video

class Video < ActiveRecord::Base      self.primary_key = "id"      has_and_belongs_to_many :categories      has_and_belongs_to_many :tags        scope :with_categories, ->(ids) { joins(:categories).where(categories: {id: ids}) }      scope :excluded_tags, -> { joins(:tags).where(tags: {id: 15}) }        scope :without_categories, ->(ids) { where.not(id: excluded_tags.with_categories(ids) ) }    end  

But when I call

    @excluded_categories = [15,17,26,32,35,36,37]      @videos = Video.without_categories(@excluded_categories)  

I still get video which has tag 15

Am I doing something wrong?

How to disable render on send_data

Posted: 31 Aug 2016 08:15 AM PDT

I am attempting to create an attachment upload and download system in a messaging system for a rails app. The application is using a salesforce database:

def download_attachment      @attachment = some_salesforce_object      file = File.open(@attachment[:Name], 'wb')      send_data file, :filename => @attachment[:Name], :disposition => 'Attachment'  end  

the link is here:

<%= link_to 'download', download_attachment_path(:letter_id => params[:letter_id], :child_id => @child.sf_id)%>   

The code above renders a blank screen with a single character : '#' and does not download the file. If I hit refresh it downloads the file properly while remaining on the plain page with the # character.

The desired behavior is that I simply click to download the attachment and it downloads without rendering anything. I have come to understand that send_data is in and of itself a render, so I imagine that I am going about this totally wrong.

Unable to pass parameters to controller in POST AJAX

Posted: 31 Aug 2016 08:01 AM PDT

I cannot pass parameters to controller action in ajax POST request. There is my code :

 $("#sendSubCatButton").click(function(){      var catId = $("#category_name").data("id");      var subCatName = $("#sous_category_name").val();      var lvlUrgenceMax = $("#sous_category_lvl_urgence_max option:selected").val();      // alert(catId);      // alert(subCatName);      // alert(lvlUrgenceMax);      $.ajax({        url: '/sous_categories',        type: 'POST',        dataType: 'json',        data: {            name: subCatName,            category_id: catId,            lvl_urgence_max: lvlUrgenceMax        }      });    });  

And my controller (only the parts concerned) :

  def create      @create_new_subcategory = verifRight('create_new_subcategory')      if @create_new_subcategory        @category = Category.find(params[:category_id])        @sous_category = SousCategory.new(sous_category_params)        # Any category have a 'lvl_urgence_max', for those who create an incident.        # With that, we can determine how many an incident is important.        @sous_category.lvl_urgence_max.nil? ? @sous_category.lvl_urgence_max = 10 : false        respond_to do |format|          if @sous_category.save            format.json { render json: @sous_category.id, status: :created }            format.html { redirect_to edit_category_path(@category), notice: 'Vous venez de créer une sous catégorie.' }          else            format.json { render json: @sous_category.errors, status: :unprocessable_entity }            format.html { redirect_to :back, notice: 'Impossible de créer la sous catégorie.' }          end        end      else        renderUnauthorized      end    end  

...

  def sous_category_params      params.require(:sous_category).permit(:name, :category_id, :lvl_urgence_max)    end  

In console there are that :

Started POST "/sous_categories" for 127.0.0.1 at 2016-08-31 16:08:56 +0200
Processing by SousCategoriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"EDqyXaq+2PekfJrLrmn/+16AnirzvySD+hkZj5+cQee2JD2ddMudDRJWXlZkCfKJ3mzw2AWuVAeCPr/y0Y1WVw==", "sous_category"=>{"name"=>"efsefesf", "lvl_urgence_max"=>"10"}}

EDIT : I commented the "alerts" but I can see the value of the var "CatId" in the alert popup but it is not passed.

How to configure routes for different user models using devise?

Posted: 31 Aug 2016 07:21 AM PDT

I have two different user groups, User and Flyer.

I have generated views and controllers for both the models using,

rails g devise:controllers users/flyers   

and for views:

rails g devise:views users/flyers  

This is my routes.rb:

Rails.application.routes.draw do      devise_for :flyers    devise_for :admins    resources :currencies    resources :broadcasts      devise_for :users, controllers: {          sessions: 'users/sessions',              registrations: 'flyers/registrations'          }      devise_for :flyers, controllers: {      sessions: 'flyers/sessions',    }  end  

But I am getting error for devise for flyers controllers route:

Invalid route name, already in use: 'new_flyer_session' You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created  

How can I have different routes? Thanks

How can I implement ADFS with a Heroku Rails app?

Posted: 31 Aug 2016 07:09 AM PDT

Our company has a Rails application hosted on Heroku. It currently uses Devise for user authentication.

One of our clients wants to know if their users could access our application using their ADFS implementation.

  1. Would we be able to use Heroku Integrated security with Identity Federation?
  2. Would we need a 3rd party like Auth0?
  3. Can Devise use ADFS?
  4. Should we use OmniAuth SAML?

Not sure where to start.

How to disable Rails 5 "X-Request-Id" header

Posted: 31 Aug 2016 06:49 AM PDT

On Rails 5, all requests includes an unique identifier accessible on application and displayed on HTTP response headers, called "X-Request-Id".

This identifier is very useful for debugging and logging, but I'm having trouble with this in a very old web client.

I tried to clear the header but it did not work.

response.headers['X-Request-Id'] = nil  

How can I remove this information from headers?

Google Analytics API with Ruby on Rails

Posted: 31 Aug 2016 06:48 AM PDT

I am trying to add Google analytics API to my Rails Appication using Oauth.

I am using google-api-client gem and using http://readysteadycode.com/howto-access-the-google-analytics-api-with-ruby as a reference.

Am able to create to create Client Object but when I am trying to access data

class GoogleController < ApplicationController      def redirect      client = Signet::OAuth2::Client.new({        client_id: GOOGLE_API_CLIENT_ID,        client_secret: GOOGLE_API_CLIENT_SECRET,        authorization_uri: 'https://accounts.google.com/o/oauth2/auth',        scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY,        redirect_uri: 'http://skreem.dev:3000/auth/google/callback'      })        redirect_to client.authorization_uri.to_s    end      def callback      client = Signet::OAuth2::Client.new({        client_id: GOOGLE_API_CLIENT_ID,        client_secret: GOOGLE_API_CLIENT_SECRET,        token_credential_uri: 'https://accounts.google.com/o/oauth2/token',        redirect_uri: 'http://skreem.dev:3000/auth/google/callback',        code: params[:code]      })        response = client.fetch_access_token!      session[:access_token] = response['access_token']        redirect_to url_for(:action => :analytics)    end      def analytics      client = Signet::OAuth2::Client.new(access_token: session[:access_token])        service = Google::Apis::AnalyticsV3::AnalyticsService.new      service.authorization = client        @account_summaries = service.list_account_summaries    end    end  

and am using correct access token but getting following error

Sending HTTP get https://www.googleapis.com/analytics/v3/management/accountSummaries?  Caught error Missing token endpoint URI.  Error - #<ArgumentError: Missing token endpoint URI.>  

Extract year from string, check if successful

Posted: 31 Aug 2016 07:23 AM PDT

I would like to check whether a year was found within a string. Something like

if string.scan(/\d{4}/).first == TRUE  

for example a string looks like "there were 3 earthquakes in 2007"

Any suggestions?

How can I convert my json response in a string

Posted: 31 Aug 2016 07:08 AM PDT

I have this in my controller:

render json: gerencia.pay_charge(params: params, body: payment)  

It returns something like that:

{"code"=>200, "data"=>{"barcode"=>"03399.75039 21000.000006 74992.301015 6 69020000002250", "link"=>"https://exmaple.com.br/emissao/110276_19_NAEMAL1/A4XB-110276-74992-XILE0"}}   

I need to return a string. How can I convert it to a string? I need return something like that:

"{"code"=>200, "data"=>{"barcode"=>"03399.75039 21000.000006 74992.301015 6 69020000002250", "link"=>"https://exmaple.com.br/emissao/110276_19_NAEMAL1/A4XB-110276-74992-XILE0"}}"  

Facets, aggregations elasticsearch error / method rails

Posted: 31 Aug 2016 06:46 AM PDT

I need to do facets for my app. For the moment, I want facets appear on the result page after search. I new on rails and sorry for my bad english, i m french.

I have 2 models : Camping.rb and Caracteristiquetest.rb. I made association has_many / belongs_to. In caracteristiquetest, I have one column camping_id and other string columns "piscine" and "barbecue".

So, after lot of tests, I found a solution to find a post with value "non" on caracteristiquetest.barbecue (see after). Now i try to implement this on app. but i always have some errors...

Error :

C:/Sites/campsite/app/models/camping.rb:66: syntax error, unexpected ':', expecting => {caracteristiquetest.barbecue : "non"}}] ^ C:/Sites/campsite/app/models/camping.rb:66: syntax error, unexpected '}', expecting keyword_end {caracteristiquetest.barbecue : "non"}}] ^ C:/Sites/campsite/app/models/camping.rb:85: syntax error, unexpected end-of-input, expecting keyword_end

How can do to fix it ? By the way, after fixing that how i can implant this on my wiew ? I want to implant this function after search to allow user to filter "barbecue" "yes" / "no".

Thanks for your help.

_search with head_plugin elasticsearch When i run this i have the good result

{  "query": {    "bool": {      "must": [        {"term":           {"caracteristiquetest.barbecue": "non"}}]    }   }  }  

campings_controller.rb

  def homesearch        @campings = Camping.custom_search((params[:q].present? ? params[:q] : '*'))    end    #Page de résultats    def result      if params[:q].blank?        redirect_to action: :index and return      else      @campings = Camping.custom_search((params[:q].present? ? params[:q] : '*')).page(params[:page]).per(14).results      end        end  

camping.rb

   mapping do     indexes :name, boost: 8     indexes :adresse     indexes :commune, boost: 10     indexes :description     indexes :nomdep, boost: 10     indexes :nomregion, boost: 10     indexes :ville_id     indexes :region_id     indexes :departement_id     indexes :latitude     indexes :longitude     indexes :etoile     indexes :user_id     indexes :caracteristiquetest_id     #On implante les données du modèle supplémentaire      indexes :caracteristiquetests, type: 'nested' do        indexes :id,   type: 'integer'        indexes :piscine, type: 'string'        indexes :barbecue, type: 'string'        indexes :camping_id, type: 'integer'      end  end      def as_indexed_json(options = {})      self.as_json(only: [:name, :adresse, :code_postale, :commune, :description, :nomdep, :nomregion, :latitude, :longitude, :etoile, :caracteristiquetest_id],      include: {caracteristiquetest: {only: [:id, :piscine, :barbecue, :camping_id]}})    end      class << self      def custom_search(query)        __elasticsearch__.search(query: multi_match_query(query),  aggs: aggregations)      end        def multi_match_query(query)        {          multi_match: {            query: query,            type: "best_fields",             fields: ["name^6", "nomdep^10", "commune^8", "nomregion^7"],            operator: "and"          }        }      end  def aggregations    {  query: {    bool: {      must: [        {term:          {caracteristiquetest.barbecue : "non"}}]    }   }  }      end    end  

homesearch.html.erb

<div class="container">      <div class="row">          <div class="search">                     <%= form_tag(result_path, method: :get) %>                          <%= text_field_tag :q, params[:q], class:"search-query form-control" %>                    <%= submit_tag "GO", class:"btn btn-danger", name: nil %>          </div>       </div>  </div>  

Rails Associations don't work

Posted: 31 Aug 2016 06:56 AM PDT

I've read through many tutorials, and copied their code exactly, yet what they claim works for them doesn't work for me.

I'm making a most basic "has_many" and "belongs_to" association, but rails refuses to acknowledge any association whatsoever.

A user "has_many" emails. Emails "belong_to" user. Here's my code:

user.rb

class User < ActiveRecord::Base    unloadable      has_many :emails    accepts_nested_attributes_for :emails,      :allow_destroy => true,    #  :reject_if     => :all_blank  end  

email.rb

class Email < ActiveRecord::Base    unloadable      belongs_to :user  end  

Then, in the console:

User.emails.build  NoMethodError: undefined method `emails' for #<Class:0x00000006c16e88>  

Indeed, this "NoMethodError" persists no matter what.

As of now, my guess is that a capacitor in my hardware burnt out while I was installing rails, causing everything to work except this one thing. Or maybe it's something else :p

EDIT:

Another console attempt:

my_user = User.new  my_user.emails.build  

Also results in an undefined "emails" method.

I noticed that my original user class has a bad comma at the end; removing that, I get this error:

ActiveRecord::UnknownAttributeError: unknown attribute 'user_id' for Email.  

Metasploit Update: Error In Bundle Install ( nokogiri 1.6.8 )

Posted: 31 Aug 2016 06:01 AM PDT

Metasploit was working Fine until this morning I updated it with msfupdate, And all went to shit.

Typing msfconsole Now gives me this error:

Could not find nokogiri-1.6.8 in any of the sources Run bundle install to install missing gems.

So I went and Typed bundle install, It was going fine until this happened:

Installing nokogiri 1.6.8 with native extensions  Gem::Ext::BuildError: ERROR: Failed to build gem native extension.  /usr/bin/ruby2.2 -r ./siteconf20160831-24032-1wim46x.rb extconf.rb --use-system-libraries  Using pkg-config version 1.1.7  checking if the C compiler accepts ... yes  Building nokogiri using system libraries.  checking for libxml-2.0... no  checking for libxslt... no  checking for libexslt... no  ERROR: cannot discover where libxml2 is located on your system. please make sure pkg-config is installed.  * 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/bin/$(RUBY_BASE_NAME)2.2      --help      --clean      --use-system-libraries      --with-zlib-dir      --without-zlib-dir      --with-zlib-include      --without-zlib-include=${zlib-dir}/include      --with-zlib-lib      --without-zlib-lib=${zlib-dir}/lib      --with-xml2-dir      --without-xml2-dir      --with-xml2-include      --without-xml2-include=${xml2-dir}/include      --with-xml2-lib      --without-xml2-lib=${xml2-dir}/lib      --with-libxml-2.0-config      --without-libxml-2.0-config      --with-pkg-config      --without-pkg-config      --with-pkg-config      --without-pkg-config      --with-override-variables      --without-override-variables      --with-xslt-dir      --without-xslt-dir      --with-xslt-include      --without-xslt-include=${xslt-dir}/include      --with-xslt-lib      --without-xslt-lib=${xslt-dir}/lib      --with-libxslt-config      --without-libxslt-config      --with-pkg-config      --without-pkg-config      --with-exslt-dir      --without-exslt-dir      --with-exslt-include      --without-exslt-include=${exslt-dir}/include      --with-exslt-lib      --without-exslt-lib=${exslt-dir}/lib      --with-libexslt-config      --without-libexslt-config      --with-pkg-config      --without-pkg-config    extconf failed, exit code 1    Gem files will remain installed in /usr/share/metasploit-framework/vendor/bundle/ruby/2.2.0/gems/nokogiri-1.6.8 for inspection.  Results logged to /usr/share/metasploit-framework/vendor/bundle/ruby/2.2.0/extensions/x86-linux/2.2.0/nokogiri-1.6.8/gem_make.out  Using rack-test 0.6.3  Using faraday 0.9.2  Using jsobfu 0.4.1  Using packetfu 1.1.11  Using rex-arch 0.1.1  Using rex-ole 0.1.2  Using rex-random_identifier 0.1.0  Using rex-zip 0.1.0  Using simplecov 0.12.0  Using activesupport 4.2.7.1  Using tzinfo-data 1.2016.6  An error occurred while installing nokogiri (1.6.8), and Bundler cannot  continue.  Make sure that gem install nokogiri -v '1.6.8' succeeds before bundling.  

So I started Searching and stuff, Came across This, suggested that I should run: bundle config build.nokogiri --use-system-libraries

But again..Nothing. I also tried gem install nokogiri -v 1.6.8, Even older versions gem install nokogiri -v 1.6.0.

I'm using Kali.

Thanks In Advance!

Can't create a route that has a segment with a leading dot in Rails (to verify Let's Encrypt)

Posted: 31 Aug 2016 05:58 AM PDT

In my Rails 5 app on Heroku, I'm trying to create a route for this URL: http://beta.example.com/.well-known/acme-challenge/some-key, so I can verify my server with Let's Encrypt to get an SSL certificate. But I can't get the route to work with a leading dot or period in any segment of the route, it just returns 404 Not Found.

In other words, the dot at the beginning of .well-known is screwing things up. I can get a route to work without the dot, or if the dot is somewhere else (e.g. well.known), but if the dot is the first character in the segment, it doesn't work.

I started with this:

get "/.well-known/acme-challenge/:id" => "pages#letsencrypt"  

When that didn't work, I tried using a (dynamic segment):

get ':letsencrypt_route/acme-challenge/:id', to: "pages#letsencrypt", letsencrypt_route: /[^\/]+/  

This will allow a dot anywhere in the segment... except as the first character, which is where I need it.

Any idea what's causing this? When I try and navigate to a URL that has a leading dot in a segment, it doesn't even show anything in my log, it's just an immediate 404.

I've seen some people having this issue on both Rails 4 and Rails 5, and it's happening for me using either Thin or Puma, and in both development and production. I've also tried using a couple of the letsencrypt gems, but it stalls at the same point.

Here is my Gemfile with the gems in both environments:

source "https://rubygems.org"    ruby "2.3.1"    gem "rails", "5.0.0.1"    gem "pg", "0.18.4" # postgresql database  gem "twitter-bootstrap-rails", "~> 3.2.2"    gem "active_median", "~> 0.1.0" # used with chartkick for graph reporting  gem "activerecord-session_store", require: false # save session to database  gem "acts-as-taggable-on", git: "https://github.com/mbleigh/acts-as-taggable-on" # tagging  gem "administrate", git: "https://github.com/heyogrady/administrate", branch: "rails5"  gem "analytics-ruby", "~> 2.0.0", require: "segment/analytics" # segment.io  gem "arel"  gem "autoprefixer-rails" # for CSS vendor prefixes  gem "bootbox-rails", "~>0.4" # wrappers for javascript dialogs  gem "bootstrap-switch-rails" # bootstrap-switch.js  gem "bourbon"  gem "bower-rails" # install front-end components  gem "browser" # For variants support  gem "carrierwave" # for handling file uploads  gem "carmen-rails" # country and region selection  gem "chartkick", "~> 1.2.4" # used to provide nice looking charts  gem "chronic" # natural language date parser  gem "codemirror-rails", ">= 5.11" # display source code in pattern library  gem "coffee-rails", ">= 4.1.1"  gem "coffee-script-source", ">= 1.8.0" # Coffee script source  gem "country_select" # HTML list of countries  gem "dalli" # for memcached  gem "delayed_job_active_record", ">= 4.1" # background job processing  gem "delayed_job_web", ">= 1.2.10" # web interface for delayed job  gem "devise", ">= 4.2.0"  gem "devise-async", git: "https://github.com/mhfs/devise-async", branch: "devise-4.x" # for user authentication  gem "flamegraph" # super pretty flame graphs  gem "fog", require: false # for handling s3  # gem "font_assets" # Handle Cross-Origin Resource Sharing on fonts  gem "font_assets", git: "https://github.com/ericallam/font_assets", ref: "457dcfddc4318e83679e9a0935612924b7717085"  gem "friendly_id", "~> 5.1.0"  gem "fullcontact" # social profile info from fullcontact.com  gem "fuzzy_match" # used by smart_csv_parser for contact & address mapping  gem "google-api-client", "< 0.9", require: "google/api_client" # connecting to Google API  gem "groupdate", "~> 2.1.1" # used with chartkick for graph reporting  gem "handy", git: "https://github.com/heyogrady/handy"  gem "hike" # finds files in a set of paths  gem "honeybadger" # for error tracking  gem "intercom-rails" # tracking user behavior  gem "jbuilder", ">= 2.4.1" # for building JSON  gem "jquery-fileupload-rails", "~> 0.4.6" # file uploads  gem "jquery-rails" # jQuery  gem "jquery-ui-rails" # jQuery UI  gem "json" # for parsing JSON  gem "kaminari" # pagination  gem "le" # logentries  gem "less-rails", ">= 2.7.1" # LESS => CSS  gem "lograge" # better log formatting  gem "mandrill-api" # sending and tracking emails  gem "mechanize" # for screen scraping  gem "memory_profiler" # lets us use rack-mini-profilers GC features  gem "mini_magick" # processing images  gem "newrelic_rpm" # monitor app performance  gem "nylas", "1.1.0" # emails, calendar, contacts via Nylas.com  gem "oink"  gem "omniauth" # third party authentication  gem "omniauth-google-oauth2" # Google authentication  gem "omnicontacts" # retrieve contacts from email providers  gem "open_uri_redirections" # allow OpenURI redirections from HTTP to HTTPS  gem "paper_trail" # maintain record of stripe plans & subscriptions  gem "prawn-labels" # PDF labels  gem "puma" # server  gem "public_activity" # for model activity tracking  gem "rack-mini-profiler", require: false # display page load time badge  gem "rack-timeout" # raise error if Puma doesn't respond in given time  gem "rack-zippy" # serve gzipped assets  gem "rails-deprecated_sanitizer" # Our app uses old sanitizer methods.  gem "react-rails", "~> 1.6.0"  gem "responders", "~> 2.0" # respond_with and respond_to methods  gem "rest-client"  gem "sass-rails", ">= 5.0.3"  gem "semantic-ui-sass", git: "https://github.com/heyogrady/semantic-ui-sass"  gem "select2-rails" # select/search/dropdown box  gem "selenium-webdriver", require: false # screen-scraping  gem "signet"  gem "simple_form", ">= 3.2.1" # forms made easy for rails  gem "sinatra", git: "https://github.com/sinatra/sinatra"  gem "stripe", "~> 1.15.0" # charging customers  gem "stripe_event" # Stripe webhook integration  gem "stackprof" # a stack profiler  gem "state_machines-activemodel", ">= 0.4.0.pre"  gem "state_machines-activerecord", ">= 0.4.0.pre"  gem "toastr-rails" # display toaster notifications  gem "therubyracer", platforms: :ruby  gem "turbolinks", "~> 5.0.0.beta" # faster page loads  gem "twilio-ruby" # phone and SMS services  gem "twitter-typeahead-rails", "~> 0.11.1.pre.corejavascript" # typeahead.js - autocomplete  gem "uglifier", ">= 1.0.3"  gem "uuidtools"  gem "valid_email" # email validation  gem "wicked" # multi-page wizard forms  gem "yaml_db", git: "https://github.com/heyogrady/yaml_db", branch: "monkey-patch-rails-5" # import/export yml->db  gem "yaml_dump", git: "https://github.com/vanboom/yaml_dump" # dump db records to yaml files  # gem "zeroclipboard-rails", "~> 0.1.1" # copy to clipboard  

How to add custom field to devise forgot my password?

Posted: 31 Aug 2016 06:02 AM PDT

Let me preface this with I am a Java developer, but my team is developing an SSO microservice for our product in rails so I am learning as I go.

Currently I have it setup to send a confirmation of password reset when a user enters their email into this form:

<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>  <%= devise_error_messages! %>      <div class="row">          <div class="medium-12 small-12">              <div class="field">                  <%= f.label :email, class: 'field-label' %>                  <%= f.email_field :email, autofocus: true %>              </div>          </div>      </div>        <div class="row">          <div class="actions columns medium-12 small-12">              <%= f.submit "Send", id: "send-button" %>          </div>      </div>        <div class="row text-center align-center">          <div class="small-8 small-centered columns">              <br><p id="form-subheading">* For security reasons, we do NOT store your password. We will NEVER send your password via email.</p>          </div>      </div>  <% end %>  

And it successfully passes through the following function in the class Users::PasswordsController < Devise::PasswordsController

# POST /resource/password  def create   super  end  

The problem is now we need to add the following first_name and last_name fields to the form, and authenticate it against the User model before sending form to their email, but it is ignoring those parameters entirely. Clearly I need a check somewhere, but have no idea where to begin.

<div class="row">      <div class="medium-5 small-12">          <div class="field">              <%= f.label :first_name, class: 'field-label' %>              <%= f.text_field :first_name %>          </div>      </div>      <div class="medium-6 medium-offset-1 small-12">          <div class="field">              <%= f.label :last_name, class: 'field-label' %>              <%= f.text_field :last_name %>          </div>      </div>  </div>  

I know they get sent to the backend because the params[:user] variable contains the information if I put a byebug statement in the function. I am just unsure how to validate the new information in the form.

Any help on building custom fields for this form would be appreciated.

Fetch Gmail, Yahoo, Hotmail contacts with pagination using OmniContacts

Posted: 31 Aug 2016 05:42 AM PDT

I'm using OmniContacts to integrate with Gmail, Yahoo, Hotmail APIs. But It's fetching all contacts of account. Some users have more than 1000 contacts.

So, I need to add pagination to send request to the API. In Gmail the gem has limit as this importer :gmail, "xxx", "yyy", :max_results => 1000. But I need to add pagination not limit.

How can I send request with pagination for Gmail API, and (Yahoo, Hotmail) APIs?

Automatic state transition after certain period of time

Posted: 31 Aug 2016 05:26 AM PDT

I am using state machine gem https://github.com/pluginaweek/state_machine.

I want to change a particular state after a certain period of time (say 2 days). Is there a way to automatically change state in background, without using job or scheduler?

Get videos which doesn't have any of given cateogires

Posted: 31 Aug 2016 05:23 AM PDT

I'm trying to get all videos with those parameters. But even tho I don't get any error I still get some videos which have category [17] for example.

  • Doesn't have any of fallowing categories [15,17,26,32,35,36,37]
  • have duration longer then 100
  • They are unique

Video.rb

class Video < ActiveRecord::Base     self.primary_key = "id"     has_and_belongs_to_many :categories  end  

Category.rb

class Category < ActiveRecord::Base      has_and_belongs_to_many :videos  end  

My Query

    @excluded_categories = [15,17,26,32,35,36,37]        @videos = Video.joins(:categories).where("duration >= 100").where.not( categories: { id: @excluded_categories } ).pluck(:video_id).uniq  

Is there better way how to write how write this query?

Rails assets precompile does not generate paths with leading /

Posted: 31 Aug 2016 04:49 AM PDT

I am using sass helpers, background-image: image-url("favicon.png") in my SCSS file.

In dev mode, the background url's are generated with the path

background-image: url(/assets/images/favicon-<uuid>.png);  

However, in production or staging, the background url's are generated with the path

background-image: url(assets/images/favicon-<uuid>.png);  

Notice that production does not have a leading slash. This leads to all kinds of havoc.

What makes image-url generate absolute vs relative path?

Cap deploy assets precompile error

Posted: 31 Aug 2016 04:48 AM PDT

I am setting up new staging server for my application. Existing staging, as well as development environments with the same release versions work fine.

Trying to cap deploy, I receive the following error:

    [1906b0ea] Command: cd /home/user/appname/releases/20160831113756 && ( export RAILS_ENV="production" ; ~/.rvm/bin/rvm 2.3.0 do bundle exec rake assets:precompile )  rake aborted!  ...  Sprockets::FileNotFound: couldn't find file 'datatables' with type 'application/javascript'  Checked in these paths:     /home/user/appname/shared/bundle/ruby/2.3.0/gems/babel-source-5.8.35/lib    /home/user/appname/releases/20160831113756/app/assets/images    /home/user/appname/releases/20160831113756/app/assets/javascripts    /home/user/appname/releases/20160831113756/app/assets/stylesheets    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/images    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/javascripts    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/media    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-datatables-rails-3.3.0/app/assets/stylesheets    /home/user/appname/shared/bundle/ruby/2.3.0/gems/cocoon-1.2.8/app/assets/javascripts    /home/user/appname/shared/bundle/ruby/2.3.0/gems/turbolinks-2.5.3/lib/assets/javascripts    /home/user/appname/shared/bundle/ruby/2.3.0/gems/jquery-rails-4.1.1/vendor/assets/javascripts    /home/user/appname/releases/20160831113756/vendor/assets/bower_components    /home/user/appname/releases/20160831113756/tmp/themes        /home/user/ap  

pname/releases/20160831113756/vendor/assets/bower_components

Here is my application.js file //

= require jquery              //= require jquery_ujs              //= require datatables              //= require turbolinks              //= require cocoon              //= require select2              //= require highcharts              //= require highcharts/highcharts-more              //= require sparklines              //= require rangeslider.js/dist/rangeslider              //= require Sortable              //= require moment              //= require pikaday              //= require tooltipster              //= require urijs              //= require jscolor/jscolor              //= require_tree .  

And here are parts of Gemfile.lock

    jquery-datatables-rails (3.3.0)        actionpack (>= 3.1)        jquery-rails        railties (>= 3.1)        sass-rails     ....         ajax-datatables-rails (0.3.1)        railties (>=   

3.1)

I've searched several SO questions, but none seem to be relevant.

Do you have any ideas on what could cause that and how to solve it?

Run before filter an large number of actions in Ruby on Rails 4

Posted: 31 Aug 2016 05:29 AM PDT

I have lots of controller in my Rails application, and I need to use a before_filter before some actions in different controllers. The before filter will execute the same code of all these actions. Is there a clean DRY way(in application_controller for instance) to specify the list of actions that should run this before_filter? I have tried to use before_filer in all controllers(9), but this looks so repetitive since it is the same code.

God Script is failing to take care of unicorn with Rails application

Posted: 31 Aug 2016 04:37 AM PDT

God Script is failing on line. I have added shell script in /etc/init.d/god-init which runs the god script which is placed in "config/unicorn.god"

pid_file = File.join(RAILS_ROOT, 'tmp/pids/unicorn.pid')    w.name = 'unicorn'  w.interval = 60.seconds  w.start = "unicorn -c #{RAILS_ROOT}/config/unicorn.rb -D"  w.stop = "kill -s QUIT $(cat #{pid_file})"  w.restart = "kill -s HUP $(cat #{pid_file})"  w.start_grace = 20.seconds  w.restart_grace = 20.seconds  w.pid_file = pid_file    w.behaviour(:clean_pid_file)  

This is giving me an error as -

Sending 'load' command with action 'leave'    undefined method `behaviour' for #<God::Watch:0x00000001faa0b8>  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god/task.rb:265:in `method_missing'  /var/www/hamperville/config/unicorn.god:15:in `block in root_binding'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:294:in `task'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:281:in `watch'  /var/www/hamperville/config/unicorn.god:3:in `root_binding'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:593:in `eval'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god.rb:593:in `running_load'  /home/ubuntu/.rvm/gems/ruby-2.2.1/gems/god-0.13.7/lib/god/socket.rb:58:in `method_missing'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1624:in `perform_without_block'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1584:in `perform'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1657:in `block (2 levels) in main_loop'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1653:in `loop'  /home/ubuntu/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/drb/drb.rb:1653:in `block in main_loop'  

Can somebody suggest if i am doing something wrong?

Insufficient validation for 'name' using / +\w/. Use \A and \z as anchors

Posted: 31 Aug 2016 04:39 AM PDT

I used brakeman for generating scanning reports in my application. It generated a Format Validation security warning with High Confidence in my model page:

Insufficient validation for 'name' using / +\w/. Use \A and \z as anchors near line 54

This is the line in my model where I am facing error:

validates_format_of :name, :with => / +\w/, :message => "must be your first and last name."  

If there is no space in the name field, I am showing above validation. How can show it \A and\z format?

File Import Modal Issues Rails 5 Bootstrap 3

Posted: 31 Aug 2016 04:19 AM PDT

So it would appear Modals are the bane of my existence lately.

I have gone over previous questions I've asked about modals, tried and tried again but this bugger just wont go.. and I'm getting some wonky server output when i try to just open the modal.

this is what the server is outputting when I click the link that should open the modal.. Note** I want the modal to open from anywhere in the app via the nav-bar.

rails server output:

Started GET "/users/import" for ::1 at 2016-08-31 05:04:14 -0600  **Processing by UsersController#show as JS** **<-- ODD AS IM NOT CALLING SHOW AT ALL.**    Parameters: {"id"=>"import"}    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]    User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."user_ident" = $1 LIMIT $2  [["user_ident", "import"], ["LIMIT", 1]]    CACHE (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."user_ident" = $1 LIMIT $2  [["user_ident", "import"], ["LIMIT", 1]]    Rendering users/show.html.erb within layouts/application    Rendered users/show.html.erb within layouts/application (12.4ms)  Completed 500 Internal Server Error in 41ms (ActiveRecord: 0.6ms)        ActionView::Template::Error (undefined method `role' for nil:NilClass):      1: <p>      2:   <strong>Role:</strong>      3:   <%= @user.role.name %>      4: </p>      5:      6: <p>    app/views/users/show.html.erb:3:in `_app_views_users_show_html_erb__3994365900320744804_70230998256260'    Rendering /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb    Rendering /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb    Rendered /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.6ms)    Rendering /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb    Rendered /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.8ms)    Rendered /Users/developer/.rvm/gems/ruby-2.3.1/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (34.7ms)  DEPRECATION WARNING: #original_exception is deprecated. Use #cause instead. (called from status_code_with_paginate at /Users/developer/.rvm/gems/ruby-2.3.1/gems/will_paginate-3.1.0/lib/will_paginate/railtie.rb:49)  

the strange thing here is that im not calling the show action at all but im seeing in the second line of the server out put its using it for some reason.

here is the import.js controller action

  def import      User.import(params[:file])      redirect_to users_path, notice: 'Users Added Successfully'    end  

and its user.rb model method.

  def self.import(file)      CSV.foreach(file.path, headers: true) do |row|        User.create! row.to_hash      end    end  

my navbar link:

<li><%= link_to "Import Users", import_users_path, remote: true %></li>  

and for now (as I just want to open the thing and i can handle the create.js) here is the import controller action (import.js.erb) -- that I thought would handle opening the modal.

$("#userImport").modal('show');  

perhaps I'm way off here but i dont see why this would be different from a standard modal with a form..??

any help is greatly appreciated.

EDIT # 1 - Adds Routes.rb and rake routes output

  resources :users do      collection {post :import}    end        import_users POST   /users/import(.:format)           users#import             users GET    /users(.:format)                  users#index                   POST   /users(.:format)                  users#create          new_user GET    /users/new(.:format)              users#new         edit_user GET    /users/:id/edit(.:format)         users#edit              user GET    /users/:id(.:format)              users#show                   PATCH  /users/:id(.:format)              users#update                   PUT    /users/:id(.:format)              users#update                   DELETE /users/:id(.:format)              users#destroy  

Rails_Admin and carrierwave multiple upload (rails 4)

Posted: 31 Aug 2016 04:11 AM PDT

I was using the Gem Administrate and decided to change for Rails_Admin. Since I have changed, almost everything work well except that I cannot upload multiple images ?

How comes? Anyone knows how to fix this? As everything worked fine... I don't know what piece of code to post, so please just ask me what would be needed :)

Thanks

Rails: mounting engine inside nested routes

Posted: 31 Aug 2016 03:58 AM PDT

I am trying to mount an engine at two different points in the same app.

The first point, which is working, is at the root level 'localhost:3000/news'.

The second is one resource deep, with the desired url structure something like this: 'localhost:3000/venues/1/news'. This is not working.

I am initialising the engine in the host app routes file like this

  mount NewsEngine::Engine => "/"     resources :venues do      mount NewsEngine::Engine => "/"     end  

Running rake routes however only yields the first level of routes.

newsitems GET  /news(.:format)              news_engine/newsitems#index                                          newsitem GET  /news/:newsitem_id(.:format) news_engine/newsitems#show   

Weirdly, referencing even the first level raises an error:

=link_to "News", intertain_news_engine.newsitems_path  => No route matches {:action=>"index"} missing required keys: [:venue_id]  

I would have expect this error trying to call venue_newsitems_path but not newsitems_path

The routes file in the engine itself looks like this.

NewsEngine::Engine.routes.draw do    resources :newsitems, param: :newsitem_id,                          only: [:index, :show],                          path: 'news'    end  

Venues are retrieved using config blocks in the host application that tell the engine to call a before_action method from the host app application controller - though I can't see how this would be a problem as it currently seems solely down to the routing.

Automatically send push notification in rails

Posted: 31 Aug 2016 04:10 AM PDT

I want to automatically send a push notification when ever the database record is updated. The push notifaction is for an android device. The records are from a Ruby on Rails application.

Any help will be appreciable .Thanks in advance.

No comments:

Post a Comment