jeudi 8 juin 2017

Where is Capistrano retrieving the IP Address from?

I have to deploy a rails app after the server had a problem, and the IP Address has changed.

I've updated the IP Address in deploy/production.rb, and also git's remote branches, to the correct value, namely 192.168.30.24, but as you can see from the following output, the deployment is failing due to trying to connect over 192.168.30.23.

Where is Capistrano retrieving 192.168.30.23 from?

INFO [fa83a838] Running /usr/bin/env git remote update as code@192.168.30.24
DEBUG [fa83a838] Command: cd /var/www/paperless_office/repo && ( export RBENV_ROOT="~/.rbenv" RBENV_VERSION="2.3.0" GIT_ASKPASS="/bin/echo" GIT_SSH="/tmp/paperless_office/git-ssh.sh" ; /usr/bin/env git remote update )
DEBUG [fa83a838]    Fetching origin
DEBUG [fa83a838]    ssh: connect to host 192.168.30.23 port 22: No route to host

Thanks

mercredi 7 juin 2017

How to know if I am using Rails 2.3 in production?

I have a client that is running a Linux VPS with a Ruby on Rails site. He said is a Rails 5 but I enter in the Linux VPS and type rails -v and I get rails 2.3.14. There is a way to prove that the site is not running rails 2.3.14? Something like to see if have turbolinks for example. Because turbolinks not exist in rails 2.3.14. Something that you can see it just looking at the web page. Some tip please.

How to bind a form of a register to the User object? - Rails

I have a Model called user and a controller called login which have one view called new.html.erb. On the view "new", I have a small form to make the user registration but I really don't know how use the form helpers to deal with it. I was reading the http://ift.tt/2s4mHts but its getting cofuse to me... I am a bachelors student in information systems!

Login controller:

class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token

  def new
    if session[:user]
      if User.exists?
        session.destroy
      end
      if @user.nil?
        session.destroy
        redirect_to new_login_path
      end
    end
  end

  def destroy
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end

  end
  private
  def login_params
    params.require(:login).permit(:email, :senha)
  end
end

The new.html.erb (i'm trying to do something like this...):

<% if flash[:notice] %>
    <div class="notice"><%= flash[:notice] %></div>
<% end %>

<%= form_with(model: user, local: true) do |form| %>
    <% if user.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(produto.errors.count, "error") %> prohibited this produto from being saved:</h2>

          <ul>
            <% user.errors.full_messages.each do |message| %>
                <li><%= message %></li>
            <% end %>
          </ul>
        </div>
    <% end %>

    <div class="field">
      <%= form.label :nome %>
      <%= form.number_field :nome, id: :user_nome %>
    </div>

    <div class="field">
      <%= form.label :email %>
      <%= form.text_field :email, id: :user_email %>
    </div>

    <div class="field">
      <%= form.label :senha %>
      <%= form.text_field :senha, id: :user_senha %>
    </div>

    <div class="actions">
      <%= form.submit %>
    </div>
<% end %>

The User Model:

class User < ApplicationRecord
  def self.validate(email,senha)
    User.find_by(email:email, senha: Digest::MD5.hexdigest(senha))
  end
end

unable to redirect to a custom action in devise registrations controller

Excuse me for the noob question.

I have a devise users model and i want to save additional data to the users model after a user signs_in/signs_up.

routes.rb

     devise_for :users,
        path: '',
        path_names: {sign_in: 'login', sign_out: 'logout',sign_up: 'signup'},
        controllers: { registrations: 'registrations

        devise_scope :user do 
             match 'users/customer' => 'registrations#customer', :via => [:get], :as => 'customer'
             match 'users/theme-selector' => 'registrations#theme_selector', :via => [:get], :as => 'theme-selector'
        end 

registrations_controller.rb

   class RegistrationsController < Devise::RegistrationsController

    protect_from_forgery :except => :create

      def customer
      @user = current_user

    if @user
       render :customer
     # render :customer
     # redirect_to controller: 'registations', action: 'theme_selector'


        else
            render file: 'public/404', status: 404, formats: [:html]
         end   


  end



    def theme_selector
         @user = current_user
            if @user
                render :theme_selector
            else
                render file: 'public/404', status: 404, formats: [:html]
             end 


       end 

       end
      end 

customer.html.erb

 <div class="container huge-top small-bottom"">
  <div class="row large-top">
    <div class="col-md-8">
    <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|  %>

 <div class="form-group">
    <%= f.label :"Contact Person" %>
    <%= f.text_field :contact, class:"form-control" %>
  </div>
  <div class="form-group">
    <%= f.label :"Business Name" %>
    <%= f.text_field :name, class:"form-control" %>
  </div>
  <div class="form-group">
    <%= f.label :phone %>
    <%= f.text_field :phone, class:"form-control" %>
  </div>
   <div class="form-group">
    <%= f.label :email %>
    <%= f.text_field :email, class:"form-control", required: true %>
  </div>
  <div class="form-group">
    <%= f.label :"Mailing Address" %>
    <%= f.text_field :address, class:"form-control" %>
  </div>
   <div class="form-group">
    <%= f.label :"Do you currently have a domain?" %>
    <%= f.text_area :domain, class:"form-control" %>
  </div>
   <div class="col-md-5">
   <!--%= f.submit '+', :name => "add_additional_fields" %-->
    <span><%= f.submit 'Save', class: "btn btn-success" %></span>
<span><!--%= link_to 'Back', customers_path, class: "btn btn-danger" %--></span>
  </div>

  </div>
  </div>
  <% end %>

I could update the users model by submitting the data inside the customer.html.erb form .now I want to redirect to the theme_selector page and then pass in the theme_id to the users model.If i use redirect_to controller: 'registations', action: 'theme_selector' in the customer action , it is skipping customer form and rendering theme_selector page.How can I make it to redirect to theme_selector after the customer form.

theme_selector.html.erb

  <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|  %>
   <div class="row">
   <div class="col-md-4 col-sm-4 top-space">
      <!-- thumbnail-->
      <div class="thumbnail image-height">
        <a href="http://theme1./" target="_blank">
          <div class="hovereffect">
            <img src="/assets/1.jpg" class="img-responsive theme" alt="">

              <div class="price-sale"><img src="/assets/new.png"></div>

          </div>  
          <div class="caption">
            <h4>Click Here</h4>
            <!--p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p-->
            <p><button class="btn-update" role="button">View</button></p>
          </div>
        </a>  
      </div>
      <div><%= f.radio_button :theme_id, 'theme-1' %> </div>
    <!-- thumbnail end -->
    </div>   
    <div class="col-md-4 col-sm-4 top-space">
      <!-- thumbnail-->
      <div class="thumbnail image-height">
        <a href="http://theme2/" target="_blank">
          <div class="hovereffect">
            <img src="/assets/2.jpg" class="img-responsive theme" alt="">

              <div class="price-sale"><img src="/assets/new.png"></div>

          </div>  
          <div class="caption">
            <h4>Click Here</h4>
            <!--p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere, soluta, eligendi doloribus sunt minus amet sit debitis repellat. Consectetur, culpa itaque odio similique suscipit</p-->
            <p><button class="btn-update" role="button">View</button></p>
          </div>
        </a>  
      </div>
      <div><%= f.radio_button :theme_id, 'theme-1' %> </div>
    <!-- thumbnail end -->
    </div>
     <div class="row">
 <div class="col-md-12 top-space"><%= f.submit 'Submit', class: "btn-addmore" %></div>
 </div>
 <% end %>

Any Help or suggestion is highly Appreciated. Thanks in Advance.

Ruby on Rails Michael Hartl chapter 9 Test fails

I was finishing up Chapter 9 from the RoR Tutorial and I was running the last test and a Failure showed up from the code which ran green in the previous tests. I searched the whole web and cross check code everywhere but I wasnt able to resolve it.

FAILURE MESSAGE:

Failure: UserTest#test_email_validation_should_reject_invalid_address [/home/ubuntu/workspace/sample_app/test/models/user_test.rb:44]: "foo@bar..com"should be invalid

user_test.eb

require 'test_helper'

class UserTest < ActiveSupport::TestCase

  def setup
    @user = User.new(name: "Example User", email: "user@example.com", password: "foobar", password_confirmation: "foobar")
  end

  test "should be valid" do 
    assert @user.valid?
  end
  test "name should be present" do
    @user.name = "   "
    assert_not @user.valid?
  end

  test "email should be present" do
    @user.email = " "
    assert_not @user.valid?
  end

  test "name should not be too long" do
   @user.name = "a" * 51
   assert_not @user.valid?
  end

  test "email shouldnt be too long" do
    @user.email = "a" * 244 + "@example.com"
    assert_not @user.valid?
  end

  test "email validation should accept valid addresses" do
    valid_addresses = %w[user@example.com USER@foo.COM A_US-ER@foo.bar.org first.last@foo.jp alice+bob@baz.cn]
    valid_addresses.each do |valid_address|
      @user.email = valid_address
      assert @user.valid?, "#{valid_address.inspect} should be valid"
    end
  end

  test "email validation should reject invalid address" do
    invalid_addresses = %w[user@example,com user_at_org.foo user.name@example. foo@bar_baz.com foo@bar+baz.com foo@bar..com]
    invalid_addresses.each do |invalid_address|
      @user.email = invalid_address
      assert_not @user.valid?, "#{invalid_address.inspect}should be invalid"
    end
  end

  test "emails should be unique" do
    duplicate_user = @user.dup
    duplicate_user.email = @user.email.upcase
    @user.save
    assert_not duplicate_user.valid?
  end

  test "passwors should be present" do
    @user.password = @user.password_confirmation = " " * 6
    assert_not @user.valid?
  end

  test "password should have minimum length" do 
    @user.password = @user.password_confirmation = "a" * 5
    assert_not @user.valid?
  end

  test "authenticated? should return false for a user with nil digest" do
    assert_not @user.authenticated?('')
  end

end

User.eb

class User < ActiveRecord::Base
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    return false if remember_digest.nil? #Add this line
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end
end

Help me out im stuck. Thanks in advance

Parsing attribute values from string [on hold]

i have string like

"Node pvq01if-yyyi04030901.pv.km.com Alert : aaa@ppk Description : \neapi unreachable for 5 minutes\n Expr: sysstat_loadavg.1 UN:step=60&s=e-4min = 1\n Value: 1 = 1\n \n Link to Epic View Graph"

I want to extract some attributes values from the above string like node=pvq01if-yyyi04030901.pv.km.com Alert=aaa@ppk

format is string is predefined

please help to find a regular expression for getting alert value and node value from the string. or help me to solve this logic.

note: white spaces should be eliminated from the values

mardi 6 juin 2017

Rails 3.2 : Duplicate entry for key index in mysql?

I am using rails 3.2. Here! I am facing a problem, stats below.

I am having two model classes RequestedTrip and TagTrip. Here! are two other models RequestedTripAgent and Tag on which I operate in before_save callback of RequestedTrip and after_update callback of TagTrip.

There is a case in which I am facing Duplicate entry problem. The case is ...

I am updating RequestedTrip object. There is a before_save callback in which I am using find_or_create_by to find or create RequestedTripAgent object. I also assigning Tags to RequestedTrip object through which another callbacks fire in TagTrip after_update. In TagTrip after_update callback, I also using find_or_create_by of same object of RequestedTripAgent.

Here I am using find_or_create_by but getting Duplicate key index error for RequestedTripAgent. What is wrong with me?

Thanks