Friday, August 5, 2016

Elastic Beanstalk: `/opt/elasticbeanstalk/containerfiles/envvars: No such file or directory` | Fixed issues

Elastic Beanstalk: `/opt/elasticbeanstalk/containerfiles/envvars: No such file or directory` | Fixed issues


Elastic Beanstalk: `/opt/elasticbeanstalk/containerfiles/envvars: No such file or directory`

Posted: 05 Aug 2016 08:14 AM PDT

I'm using Elastic Beanstalk to deploy a Rails app. I'm trying to setup Sidekiq too, using script below. However I keep getting error /opt/elasticbeanstalk/containerfiles/envvars: No such file or directory. I SSH into the EC2 instance and the directory does exist. I'm not sure what did I do wrong here

Gist I'm currently using

Errors I'm getting:

ERROR: [Instance: i-03a6fa2e1b96474be] Command failed on instance. Return code: 10 Output: (TRUNCATED)...hooks/appdeploy/post/50_restart_sidekiq: line 3: /opt/elasticbeanstalk/containerfiles/envvars: No such file or directory  /opt/elasticbeanstalk/hooks/appdeploy/post/50_restart_sidekiq: line 7: cd: HOME not set  Could not locate Gemfile or .bundle/ directory.  Hook /opt/elasticbeanstalk/hooks/appdeploy/post/50_restart_sidekiq failed. For more detail, check /var/log/eb-activity.log using console or EB CLI.  

RSpec stub object that doesn't exist yet

Posted: 05 Aug 2016 08:07 AM PDT

I'm needing to stub an ActiveRecord model before it has been retrieved from the db. Here's a simplified example:

model.rb:

class Model < ActiveRecord::Base    def self.first_bar      find(id: 1).bar    end      def bar      'not the value I want'    end  end  

model_spec.rb:

let(:model) { Model.create } # => <Model id:1>  before { allow(model).to receive(:bar).and_return('the value I need stubbed') }    it { expect(Model.some_value).to eq('the value I need stubbed') }  

Obviously, this test fails because the object that is retrieved in Model.first_bar is a different object than the one that was stubbed.

Caveats:

  • I can't use allow_any_instance_of(Model).to receive(:first_bar) because I'm using other instances of that model elsewhere in the real test.
  • I can't use allow(Model).to receive(:first).with(id: 1) because for my use case, it's too brittle.

Ideally, I need something like allow_any_instance_of(Model).with_attributes(id: 1), so any object with those particular values gets stubbed.

Setting a blank custom header in ruby on rails

Posted: 05 Aug 2016 08:11 AM PDT

I'm writing a REST server using Ruby on rails.

Some of the communication with the client is by setting certain custom headers to predefined values. In certain situations the server is expected to respond with a custom header that is an empty string. My problem is that rails seems to omit any blank headers from the response (it will even omit a whitespace header).

This is my current code:

def respond_conflict      response.headers["CUSTOM-HEADER"] = ""      render :nothing => true, :status => 409 and return  end  

Is there some way to configure rails to still send headers even if they are empty?

Sending form data from one user to another

Posted: 05 Aug 2016 07:50 AM PDT

I am starting out on Rails and curious about how to build this system. I want User1 to fill out a form (their name, job title, and a message) and when they hit a "Send" button, it would pop up on User2's table to view. I would also want User1 to be able to send their form data to people with different roles (supervisor, assistant accountant, head sales, etc) User2 would have a 'view message' button and a 'delete message' button. I'm thinking User2 would have a desktop widget to view and delete messages.

How would you build this? Just trying to learn more and thanks in advance from a beginner!

How to get uploaded file path from Carrierwave in jquery in Rails

Posted: 05 Aug 2016 07:42 AM PDT

Im using Carrierwave on Rails to handle file upload.

It's working well and I want to make new feature on my app to display uploaded file with jquery (kind of preview uploaded file)

Therefore, I have to pass uploaded file url to the script Unfortunately, I have no idea how to do it.

File upload model

class OrderFile < ActiveRecord::Base      belongs_to :order      validates :file, presence: true      mount_uploader :file, StLuploaderUploader  end  

Form to upload new file

  <%= form_for OrderFile.new, html: { multipart: true }, :url => url_for(:controller => 'order_files', :action => 'create') do |f| %>        <%= f.file_field :file, class: "form-control" %>    <% end %>  

jquery File Upload call

jQuery(function() {      return $('#new_order_file').fileupload({          autoUpload: true,          add: function(e, data) {              var file, types;              types = /(\.|\/)(png|jpg|)$/i;              file = data.files[0];              if (types.test(file.type) || types.test(file.name)) {                  data.context = $(tmpl("template-upload", file));                  $('.CO-file_upload_progress').append(data.context);                  data.submit();              } else {                  return alert("Not supporting");              }          },          progress: function(e, data) {              var progress;              if (data.context) {                  progress = parseInt(data.loaded / data.total * 100, 10);                  return data.context.find('.bar').css('width', progress + '%');              }          },          done: function(e, data) {              $.each(data.files, function(index, file) {                  prepare_file(file); // passing file to the function              });          }      });  });  

Function to preview file

function prepare_file(file) {      loaded(file.url, "model-preview"); // I need an absolute path to the uploaded file to be passed here - file.url is not working  };  

how to show event in colorbox when clicked from calendar

Posted: 05 Aug 2016 07:34 AM PDT

this is the code that renders the fullcalendar

<br><br>  <%= link_to 'View Events', events_path, class: 'btn btn-md btn-default' %>   | <%= link_to 'New Event', new_event_path, class: 'btn btn-md btn-success',  data: {colorbox: true}, colorbox_iframe: true %>  <br><br>  <div id="calendar" style="width: 400px; height: 400px"></div>  

i modified index.json.jbuilder file

json.array!(@events) do |event|    json.extract! event, :id, :title, :description    json.start event.start_time    json.end event.end_time    json.url event_url(event, format: :html)  end  

this is the application.js file

//= require jquery  //= require jquery_ujs  //= require twitter/bootstrap  // require turbolinks  //= require moment  //= require fullcalendar  //= require colorbox-rails  //= require_tree .    $(document).ready(function() {      $('#calendar').fullCalendar({          events: '/events.json'      });  });  

My events are showing nicely on the calendar, but how do i make them appear in a colorbox when clicked from the calendar. I have correctly applied colorbox for other pages, but how do i do the same from the calendar??? Anyone pls?

Color formatting for the running balance in rails 4.2

Posted: 05 Aug 2016 07:26 AM PDT

Actually I have running balance in my statement and it reflects with colour that is when balance is positive it is black and when balance goes negative it becomes red.

I would like to have same formatting to be applied when running balance is out of the statements table.

Right now it shows '-' sign for negative values but I want to have to be in red colour without '-' negative sign.

Please refer the screen-shot for better understanding as shown below;

screenshot.png

Running balance inside the table body;

<tr>  <% @balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>        <% color = @balance >= 0 ? "pos" : "neg" %>        <td class="col-1 <%= color %>"><%= number_with_precision(@balance.abs, :delimiter => ",", :precision => 2) %></td>  </tr>  

Running balance outside the table body;

<center><p><b><%= number_to_currency(@balance, :unit => 'AED ', :delimiter => ",", :precision => 2) %></b></p></center>  

How do I retrieve the same formatting for the running balance in both the places.

Any suggestions are most welcome.

Thank you in advance.

How can I embed facebook videos on my blog by using the ruby gem red carpet?

Posted: 05 Aug 2016 07:16 AM PDT

I figured out how to embed youtube videos by simply pasting the url of a video into the form. Therefor I used the following function in the appliaction_helper:

def url_link(link)    if link.include?("https://www.youtube.com")      youtube_link(link)    else      normal_link(link)    end  end    def youtube_link(link)    parameters_start = link.index('=')    video_id = link[parameters_start + 1..-1]    "<iframe width=\"100%\" height=\"400\"src=\"https://www.youtube.com/embed/#{video_id}?autoplay=0\" allowfullscreen></iframe>"  end  

Now I'd really like to know how to achieve this with facebook videos. Does anyone know an easy way how to embed them? (Using an ruby on rails application with the red carpet gem)

Why does not the remote form with Turbolinks 5?

Posted: 05 Aug 2016 06:48 AM PDT

On page viewing post (show) there is add a comment form:

<form id="js-comment-form" action="/post/45/comment" accept-charset="UTF-8" data-remote="true" method="post">

If the load (or reload) the page, the form will work.

If you go out of the list of posts (index) page on the post (show), then the form will not work.

By clicking on the "Send" button nothing happens.

What is the problem?

Devise secures all routes by default?

Posted: 05 Aug 2016 07:59 AM PDT

Is it normal behaviour for Devise to authenticate all requests to all routes after install? I have just installed Devise and not yet set a single before_action :authenticate_user! but every request sends me to the signin view.

I have also installed the simple_token_authentication gem.

Any idea what could be wrong?

Rails OmniAuth Facebook 'Redirect URL must be absolute'

Posted: 05 Aug 2016 06:30 AM PDT

I am trying to set up omniauth to allow users to sign in to my website with facebook. I get the following error when i click on the log in button after following the Github Tutorial

enter image description here

In my devise.rb file i have:

  config.omniauth :facebook, "*****", "*****",              callback_url: "CALLBACK_URL"  

I am using ngrok so i am able to test with a url that isnt localhost. The url generated is http://46cbf60d.ngrok.io

In the facebook dashboard settings i have: enter image description here enter image description here

And in the facebook dashboard 'products/facebook login' i have enter image description here

Does anybody know how to fix this error?

Ruby on Rails. Replace **Bold** with <b>Bold</b> with gsub()

Posted: 05 Aug 2016 07:01 AM PDT

In my text_area/text_field I want to give users option to add bold around some words. It would work like: This has a ** bold ** word inside.

I have used .gsub('**', '<b>').html_safe It almost works, but the problem is that the output is not exactly correct.

Expected Output: This has a bold word inside.

What I get: This has a bold word inside.

html:

<p>This has a <b>bold<b> word inside</b></b></p>  

How can I make only the words that is surrounded with ** get <b> </b>

Undefined local variable or method for module

Posted: 05 Aug 2016 07:31 AM PDT

I have module CurrencyExchange with following methods

 CURRENCIES = %w(uah rub eur usd)     def available_currencies     CURRENCIES.join(' ').downcase.split.permutation(2).map{|c|c.join('_to_')}   end  

and when i want to use available_currencies with

define_method

 available_currencies.each do |(c1, c2)|      define_method(:"#{c1}_to_#{c2}") do |cr| ... end end  

i have got an error

undefined local variable or method `available_currencies'   for CurrencyExchange:Module (NameError)  

but when i use it like

     CURRENCIES.join(' ').downcase.split.permutation(2).map{|c|c.join('_to_')}.each do |(c1, c2)|    define_method(:"#{c1}_to_#{c2}") .... end end   

it works fine

Why it happens?

Specify width in link_to image_tag

Posted: 05 Aug 2016 06:30 AM PDT

I am using the following code to link to logo on the nav bar:

 <%= link_to " #{image_tag ("logo3.svg")}".html_safe, root_url %>  

I need to specify the width of the logo, but have got a little confused. Tried in/out of the brackets, with a trailing comma - breaks every time.

Any ideas?

Active Admin: Multiple Actions in same column similar to View, Edit, Delete

Posted: 05 Aug 2016 06:36 AM PDT

I am using active admin gem to have a admin console for my ruby on rails application. I am having a problem where i want to have multiple custom actions to every item on index page just like View,Edit, Delete. But when adding custom action only the last one is displayed instead of all.

 index do       column 'Instructor Name',:user     column 'Email Address', :email     column 'Phone Number', :phone     column 'website', link_to 'google', 'www.google.com'      column :bio     actions defaults: false do |application|       if application.user.instructor == 2         button_to  'Disapprove', instructor_deny_user_path(application.user.id), method: :put       else         button_to  'Approve', instructor_approve_user_path(application.user.id), method: :put       end        link_to "resume",getresume_instructor_applications_path(id: application.id)     end    end  

Only resume link is shown instead of Approve/Disprove and resume

What am i doing wrong

How to redirect to external service page on post request?

Posted: 05 Aug 2016 05:51 AM PDT

I am posting some information to some external service, upon which it process the post params and should show its own page with the parameters I have sent.

i.e It should be redirected to their site upon post request from my side.

Here's what I am doing: I am using HTTParty to post the data to the their URL and storing the response in response object and using render :html to render to response.

I am getting a their html in response object.

here's the code:

     example_url = 'https://www.example.com/service.aspx'    post_params = build_params # builds params for post request    response = HTTParty.post(cams_url_two,                  body: URI.encode_www_form(post_params),                  headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },                  verify: false)    @result[:url] = response.body  

And in controller I am using render

render html: result[:url].html_safe  

However, what is happening here is the response returns html which is rendered on my own application i.e localhost, it is also trying to search its assets in my app.

What is expected here is upon hitting a post request it should redirect to their site.

Any advice or help on how do I do achieve this?

Thank You!

how to make this image hover effect like the airforce website?

Posted: 05 Aug 2016 05:47 AM PDT

I keep trying but in vain I have 5 images side by side and want to make a hover width effect like the airforce website in section two...here is the website: https://www.airforce.com/ scroll down and you will see 5 images side by side and when you hover on an image the width expand without effecting the image itself..I keep trying but the image get effected always..I tried putting each image on bootstrap container and make the width effect on the container itself but the images keep expand as well,and here is my website on production: https://agile-coast-64468.herokuapp.com/ here is my home page:

<div class="container-fluid" id="width-r">    <div class="this">      <%= image_tag("wood1.jpg", class: "inside")  %>    </div>    <div class="this">      <%= image_tag("wood2.jpg",class: "inside" ) %>    </div>    <div class="this">      <%= image_tag("wood3.jpg", class: "inside")  %>    </div>    <div class="this">      <%= image_tag("wood4.jpg", class: "inside")  %>    </div>    <div class="this">      <%= image_tag("wood5.jpg", class: "inside")  %>    </div>    </div>  <div class="jumbotron">    <h1 align="center"> Here come the ads</h1>  </div>  

and here is my css :

@import "bootstrap-sprockets";  @import "bootstrap";    .navbar {    background-color: #fff;  }    body {    height: 100%;  }    .width-r {    position: relative;  }  #clip {    position: absolute;    clip: rect(0, 0, 581.55px, -100px);   /* clip: shape(top, right, bottom, left); NB 'rect' is the only available     option */  }  .this {    width: 20%;    float: left;    height: 581.55px;    position: relative;    padding: 0;    }  .inside {    width: 100%;    float: left;    height: 581.55px;    position: absolute;    transition: 0.5s;  }    .inside:hover {    z-index:100;    width: 110%;  }    .navbar-ma {  /* remove space between the navbar and the images below */    margin-bottom: 0px;  }    .jumbotron {    height: 220px;    margin-bottom: 0px;    z-index: 0;  }    .container-fluid {    padding: 0px;  }  

Search over 2 joins using Sunspot/Solr

Posted: 05 Aug 2016 05:36 AM PDT

I have 3 models (Rails) defined like so:

class ModelA    belongs_to :model_b    searchable do      integer :model_b_id    end  end    class ModelB    has_many :model_a    has_many :model_c  end    class ModelC    belongs_to :model_b    #has attributes: attr1      searchable do      integer :attr1    end  end  

I'm trying to search ModelA, but using ModelB#id and ModelC#attr1. I tried to do 2 joins (ModelB being in the middle), but it didn't work:

class ModelB    searchable do     join(:attr1, target: ModelC, type: :integer,                          join: {from: :model_c_id, to: :id})    end  end    class ModelA    searchable do     join(:attr1, target: ModelB, type: :integer,                          join: {from: :id, to: :model_b_id})    end  end    ModelA.search do    with(:model_b_id, 10)    with(:attr1, 5) #this should search through ModelB and then ModelC  end  

Is this possible with Sunspot/Sorl?

Possible workaround: I think I will have to index ModelC's data at least in ModelB and make a regular join. Or even index the data directly in ModelA.

Redirect in routes.rb with wildcard values instead of params?

Posted: 05 Aug 2016 05:50 AM PDT

To redirect in routes.rb with params we use following syntax.

get '/stories/:name', to: redirect('/articles/%{name}', status: 301)  

If I want to pass the wild card url How can i do it. I tried the following it is not working.

get '/stories/*search', to: redirect('/articles/%{search}', status: 302)    get '/stories/*search', to: redirect("/articles/#{search}", status: 302)  

I there any hack around for this .

Alternative for storing information between sessions similar to redis

Posted: 05 Aug 2016 05:26 AM PDT

For my project I use an external API. On every call the API provides a token so that the next time you request data they don't have to dump all data but just the updates. I would like this data to persist between different server sessions in development. On my mac OS I use redis for such things and store the tokens under keys, I am currently developing on windows and can not install any type of redis alternative, what would be best practice for these scenarios? Should I store this information in the DB or are there more efficient and cleaner ways?

Carrierwave does not fallback to default_url even if file is missing

Posted: 05 Aug 2016 05:18 AM PDT

I'm using carrierwave (0.10.0) with Fog for S3 uploads. Implementing simple uploader:

class AvatarUploader < CarrierWave::Uploader::Base    def default_url(*_args)      "#{Rails.configuration.cdn_url}/no-image.png"    end      def extension_white_list      %w(jpg jpeg gif png)    end  end  

and mount it here

class User    include Mongoid::Document      field :name, type: String    mount_uploader :avatar, AvatarUploader  end  

When Im trying to set remote image even if no image is presented it doesn't fallback to default_url and simulates generation of file in S3 which is actually not there.

Example:

u = User.find('1234567')  u.remote_avatar_url = 'http://non-existing-url.com/avatar.jpg'  u.save!  

And when I access after reloading document

u.reload  u.avatar.url # output https://ourcdn.url/somebucket/avatar.jpg  

But when access it in the browser it's showing 404. Any ideas?

Rails 5 on Bluehost

Posted: 05 Aug 2016 04:55 AM PDT

I currently have a Rails 4.2.6 app running on Ruby 2.3.1 on Bluehost after following this tutorial: http://www.haydonryan.com/installing-ruby-2-1-1p76-and-rails-4-0-4-on-bluehost/

I am trying to update to Rails 5 app i get this error:

Rails 5 requires Ruby 2.2.2 or newer. You're running ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-linux] Please upgrade to Ruby 2.2.2 or newer to continue.  

Its showing the default version of Ruby, not my custom build. I figure it is probably an issue with my .htaccess and .bashrc files, but for the life of me i can't find a combination that works.... the strange thing is I have had the customs Ruby running for over a year without issue for the Rails 4.2.6 app. this is what I have so far:

.htaccess in my rails app/public directory:

AddDefaultCharSet utf-8  RewriteEngine On  RailsEnv development  RackBaseURI /  SetEnv GEM_HOME /home/mydomain/ruby/gems  SetEnv GEM_PATH /home/mydomain/ruby/gems:/lib64/ruby/gems/1.9.3  SetEnv RAILS_RELATIVE_URL_ROOT /store  PassengerAppRoot /home/mydomain/rails_apps/my_rails5_app  Options -MultiViews  PassengerEnabled On  PassengerResolveSymlinksInDocumentRoot On  

and the .bashrc file in the root of my account (my rails app runs in an anon domain)

# .bashrc    # Source global definitions  if [ -f /etc/bashrc ]; then      . /etc/bashrc  fi    export HPATH=$HOME  export GEM_HOME=$HPATH/ruby/gems  export GEM_PATH=$GEM_HOME:/lib64/ruby/gems/1.9.3  export GEM_CACHE=$GEM_HOME/cache  export PATH=$HPATH/ruby/bin:$PATH  export PATH=$HPATH/ruby/gems/bin:$PATH  export PATH=$HPATH/ruby/gems:$PATH      PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting  

and for completion, the .webrc file:

gem: --remote --gen-rdoc --run-tests  gemhome: /home4/thejigsa/ruby/gems  gempath: []    rdoc: --inline-source --line-numbers  

any pointers would be greatly appreciated, I spent a whole day on this, manually installing gems/ changing the .bsahrc/.htaccess files with no luck...

Include CSS and Javascript Plugins in Ruby on rails

Posted: 05 Aug 2016 06:55 AM PDT

I'm using a HTML, CSS, JS template to create the view for my Rails application. This template requires some plug-ins (mixed between CSS and JS files). I put these plug-ins in "/assets/plugins/" folders and make the call

<script type="text/javascript">var plugin_path = 'assets/plugins/';</script>      <script type="text/javascript" src="assets/plugins/myplugin/myplugin.js"></script>  

and it does not work. How can I call these plug-ins from my *.html.erb file?

How to click(using js) on element selectized with selectize.js

Posted: 05 Aug 2016 08:00 AM PDT

We are using selectize.js to make select tags on our page. The problem with it is that there are made(those divs with options) when you click on select input so there are not in DOM after page load.

What I need is to click (using javascript) on specified option after page load, but what I tried did nothing. (I want to pre-fill form when someone enters the page)

Here's some code I've tried:

$('.selectize-input').first().click()  $("div[data-value='#{ob['shipping']['country_label']}']").first().click()    # --------------------  $('.selectize-input').first().click()    $('.selectize-dropdown').first().bind 'afterShow', ->      $(document).on 'click', "div[data-value='#{ob['shipping']['country_label']}']", ->        @.click()  # --------------------  

(but @ in @.click() actually means selectize-dropdown?)

I've also tried populate all needed inputs, but it didn't work neither.

  $('.selectize-dropdown').first().click()    $('.selectize-dropdown-content').first().click()    $('.selectize-dropdown-content .option').each (idx, el) ->      if $(el).text() == "#{ob['shipping']['country']}"        $(el).addClass('selected')        return true;      else        $(el).removeClass('selected')      $('#shipping_detail_shipping_country option').first().val(ob['shipping']['country_label']).text(ob['shipping']['country'])    $('.selectize-input .item').data('value', ob['shipping']['country_label']).text(ob['shipping']['country'])  

Any help would be appreciated!

EDIT

<div class="selectize-control single">     <div class="selectize-input items required not-full has-options"       <input style="width: 41px; opacity: 1; position: relative; left: 0px;" placeholder="Kraj..." tabindex="" autocomplete="off" type="text">     </div>       <div style="display: none; width: 1158px; top: 52px; left: 0px; visibility: visible;" class="selectize-dropdown single">        <div class="selectize-dropdown-content"><div data-group="Europa" class="optgroup">          <div class="optgroup-header">Europa</div>          <div data-value="AL" data-selectable="" class="option">Albania</div><div data-value="AD" data-selectable="" class="option">Andora</div>  ...  

This is my select tag.

This is my coffee:

$('.selectize-input').first().click()    $('.selectize-control').on 'click', "div.option", =>      console.log("AA")      console.log(@)      $("div[data-value='#{ob['shipping']['country_label']}']").click()  

First line open select list, but rest do nothing. Nothing in console, nothing on page. Am I missing something?

Convert expects to assert + Integration Testing

Posted: 05 Aug 2016 04:23 AM PDT

I'm using mocha and pry gem for below syntax

Test::Token.expects(:retrieve).with(token).returns(token)  

but Now, I don't want to use gem. If I remove gem then I'm getting

uninitialized constant Minitest::Mock  

I don't want to use mocha and pry gem. So how can I convert this syntax that run without mocha and pry gem.

Test::Token.expects(:retrieve).with(token).returns(token)  

Rails app not reflecting recent changes at all

Posted: 05 Aug 2016 04:10 AM PDT

I have a rails(Rails 3.2.12, ruby 1.9.3p547) app running on AWS ubuntu cloud server, with nginx as app server and unicorn as reverse proxy server. I have made few changes in the view file but those changes are not reflecting on browser. Code is currently live ("env=production")

I tried

sudo service my_app restart  [sudo] password for me:  Shutting down my_app: Starting my_app: Already running                                                             [  OK  ]  $  sudo service nginx restart  Stopping nginx:                                            [  OK  ]  Starting nginx:                                            [  OK  ]  $  

but still got no help its still rendering the previous one. I tried commenting the whole controller file for the same view but still the app is not showing any error. I have confirmed that the app is running from the same folder in which I am making changes

I got stuck at this point please help. Thanks in Advance

"rails new [Blah]" No such file

Posted: 05 Aug 2016 04:31 AM PDT

So I'm new to Ruby and also to Rails. I have recently installed Ruby on Arch Linux. It was mostly all fine any happy except for a few errors here and there but now when I try initializing a new rails app using rails new AppName I get the error

bash: /home/[username]/.gem/ruby/2.3.0/bin/rails: No such file or directory  

I've tried creating a file and directory called rails in but get more errors.

reinstalling rails same outcome

reinstalling ruby same outcome

following any other dependencies at install also leads no wear.

Ask for any info you may need. Thanks in advance

I18n translation with i18n-active_record: same form for same key

Posted: 05 Aug 2016 04:03 AM PDT

I am working on an app in Rails 4 using i18n-active_record 0.1.0 to keep my translations in the database rather than in a .yml-file. It works fine.

One thing that I am struggling with, however, is that each translation record is one record per locale, i.e.

#1. { locale: "en", key: "hello", value: "hello")  #2. { locale: "se", key: "hello", value: "hej")  

which makes updating them a tedious effort. I would like instead to have it as one, i.e.:

{ key: "hello", value_en: "hello", value_se: "hej" }  

or similar in order to update all instances of one key in one form. I can't seem to find anything about that, which puzzles me.

Is there any way to easily do this? Any type of hacks would be ok as well.

How to handle LDAP Authentication errors in rails4

Posted: 05 Aug 2016 03:58 AM PDT

In my rails4 application i am using 'devise_ldap_authenticatable' gem. Login parameters are username and password. In the application, i need to fetch 'Email' parameter and need to store in the db.

email =  Devise::LDAP::Adapter.get_ldap_param(self.username,"mail")  if !email.blank?    self.email = Devise::LDAP::Adapter.get_ldap_param(self.username,"mail").first  end  

Email Field is mandatory to login into the application. So in the user.rb , model validation is given for the email field as:

validates :email, presence: true, length: { maximum: 100 }  

In ldap_before_save method , i will get the parameter Email if that entry exists in LDAP. But if Email is not present i am getting Raw Error page with validation error "Validation failed: Email can't be blank".

If i assign a default mail id, the issue solves, but we require the user to enter their mail and continue with the normal ldap authentication process. So how can i handle this error.

Please help. Thanks in advance.

elegant way to add css class in rails partials

Posted: 05 Aug 2016 04:06 AM PDT

I have partials which display in sidebar like below

__side_bar_partials.html.erb

<div class="col-sm-3">    <div class="account-left">                    <ul>        <li class="active"><a href="menu1">Menu1</a></li>        <li><a href="menu2">Menu2</a></li>        <li><a href="menu3">Menu3</a></li>        <li><a href="menu4">Menu4</a></li>        <li><a href="menu5">Menu5</a></li>      </ul>    </div>  </div>  

now what i need when i render this partial i want to add css class active added on selected menu

right now i render it with normal way

 <%= render "profile_sidebar"%>  

what i need to include in above code so it will add active class on selected menu

No comments:

Post a Comment