vendredi 31 mai 2019

How to Insert code after fork on PhusionPassenger.on_event()

Is there a parameter for PhusionPassenger.on_event that will act for after_fork? instead of :starting_worker_process

I would like to monkey patch class and method of rails controllers and models that run in passenger. The problem is that the rails will reloads if the rails noticed an updates in class or controller and model while the passenger creates new process that gives me a hard time since the monkey patched classes where reset to original.

Is there a way how to do it?

jeudi 30 mai 2019

How to generate destroy path for delete method when there's no destroy path on rails

I was trying to build a simple rails app with create, edit, delete method in, but when I checked on the routes the destroy method seems to missing as below;

DELETE /products/:id(.:format)  products#destroy``` 
where the delete path is missing whereas my routes file has contains . 
```  resources :products, only: [:index, :show, :new, :create, :destroy, :edit] ```

my question is:
I was wondering how do I do to create the missing destroy path and why is the reason even if i did resources on products i have still not get product delete path.

thank you so much!

Rails active-record array gives 0 on count but record exists in db?

can anyone help me to solve this mystery?

checkout on image you will understand it

Ruby version - 2.6.0 Rails - 5.2.2

enter image description here

Custom strategyfor Omniauth

I need to implement a custom strategy for an app in rails, The version of the software: Rails 5.0.7.2 ruby 2.3.2p217 (2016-11-15 revision 56796) [x86_64-linux] Bundler version 1.16.6

These are the files I added:

# config/initializers/omniauth.rb
module OmniAuth
  module Strategies
    # tell OmniAuth to load our strategy
    autoload :Platform, 'lib/strategies/platform.rb'
  end
end

Rails.application.config.middleware.use OmniAuth::Builder do
  # pass the 2 parameters to the constructor
  provider :platform, "Client Id", "Client Secret",
      client_options: {
        site: "https://my.auth.provider",
        user_info_url: "/connect/userinfo"
      }

end

Now, in my lib/strategies/ directory I created my strategy file:

# lib/strategies/platform.rb
require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Platform < OmniAuth::Strategies::OAuth2
      option :name, :platform

      option :client_options, {
        :site => "https://my.auth.provider",
        :authorize_url => "/connect/authorize",
        :user_info_url => "/connect/userinfo"
      }

      uid { raw_info["id"] }

      info do
        {
          :email => raw_info["email"]
          # and anything else you want to return to your API consumers
        }
      end

      def raw_info
        @raw_info ||= access_token.get('/connect/userinfo/me.json').parsed
      end

      def callback_url
        full_host + script_name + callback_path
      end
    end
  end
end

And I registered the callback URL in the config/routes.rb:

#OAuth2 Generic
get "/auth/:provider/callback" => "sessions#create"

Now, this app I am trying to configure, has already devise and omniauth enabled for Google, Twitter and Facebook, but for some reason, my URL does never get registered. What am I missing? what should I do? I want to have

user_platform_omniauth_authorize_path and
user_platform_omniauth_callback_path

Registered routes for my app

mercredi 29 mai 2019

how do i redirect to home page(root )when user signed out?

I am trying to get devise working on my simple rails app where;

1.I'd like when user_signed out it will redirect to home page(root).for the moment it's showing the page as many thanks!

and 2.when the user create his/her own products, the products will "only" display in the person's dashboard.(at the moment the added products will automatically added to the products index page)

<header class="navbar">



  <nav class="menu">
    <ul>
      <li>
        <a href="#"> Products <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
          <ul>
            <li>
              <%= link_to "Create a product",new_product_path %>
             </li>
            </li>
            </li>
            <li>
              <%= link_to "View all the products", products_path%></i>
            </li>
          </ul>
      </li>
      <li>
        <a href="#">Profile <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
        <ul>
          <%= link_to "My dashboard", profile_path %>
          <%= link_to "Log out", destroy_user_session_path, method: :delete %>
        </ul>
      </li>
      <li><a href="#">Contact </a></li>
    </ul>
  </nav>


</header>

<h2>Log in</h2>


<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
  <div class='signup_create_product'>
    <%= f.input :email,
                required: false,
                autofocus: true,
                input_html: { autocomplete: "email" } %>
    <%= f.input :password,
                required: false,
                input_html: { autocomplete: "current-password" } %>
    <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Log in" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>



class ProductsController < ApplicationController

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end


  def create

     @product = Product.new(product_params)
     @product.user = current_user

    if @product.save
      redirect_to products_path
    else
      render :new
    end
  end

  def edit
    @product = Product.find(params[:id])
  end



  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to products_path
  end

  private

  def product_params
    params.require(:product).permit(:product_name, :description)
  end
end

user show page

 <h1><%= @user.name %></h1>

mardi 28 mai 2019

FactoryGirl.create not working as expected

While writing rspec test cases, I am stuck at this point, where factory girl is creating instances for one model and not for another.

let!(:server) { FactoryGirl.create(:server, 
                  account: account, 
                  key: 'vm-999') }
let!(:host) { FactoryGirl.create(:host,                                      
                  account: account,
                  key: 'host-9') }

After these, when I query server from db, I am getting this object but when I query host, I am getting nil. I am not sure whether factory girl is creating the instance or not.

I am doing reload in Rspec.configure

 FactoryGirl.reload
 FactoryGirl.lint

What am I missing ?

How do I found out how many records of 1 model have associated objects of an association?

I have two models - Property & Photos.

class Property < ActiveRecord::Base
  has_many :photos, dependent: :destroy
end

class Photo < ActiveRecord::Base
  belongs_to :property
end

All I want to do is create a scope that returns only the Properties that actually have photos (i.e. photos.count > 0).

I have tried a million iterations of queries, and they don't work for one reason or another.

See some examples of what I have tried and the results:

[32] pry(main)> Property.includes(:photos).where('photos.count > 0').count
   (4.1ms)  SELECT COUNT(DISTINCT "properties"."id") FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
[33] pry(main)> Property.joins(:photos).where('photos.count > 0').count
   (11.1ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...

[38] pry(main)> Property.joins(:photos).count("properties.id").count
   (158.2ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `count' for 72604:Fixnum
from (pry):38:in `__pry__'
[39] pry(main)> Property.joins(:photos).count("properties.id")
   (50.6ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
=> 72604
[40] pry(main)> Photo.joins(:properties).count("photos.id")
ActiveRecord::ConfigurationError: Association named 'properties' was not found on Photo; perhaps you misspelled it?
from /.rvm/gems/ruby-2.3.7@myapp/gems/activerecord-3.2.22.5/lib/active_record/associations/join_dependency.rb:112:in `build'
[41] pry(main)> Photo.joins(:property).count("photos.id")
   (65.0ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604
[42] pry(main)> Photo.joins(:property).count("photos.id")
   (60.5ms)  SELECT COUNT(photos.id) FROM "photos" INNER JOIN "properties" ON "properties"."id" = "photos"."property_id"
=> 72604
[43] pry(main)> Property.joins(:photos).count("properties.id").distinct
   (46.4ms)  SELECT COUNT(properties.id) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id"
NoMethodError: undefined method `distinct' for 72604:Fixnum
from (pry):43:in `__pry__'
[44] pry(main)> Property.joins(:photos).distinct.count("properties.id")
=> 0

This should be simple, but for some reason it's much more difficult than I expected.

Thoughts?

lundi 27 mai 2019

How can i display a particular product?

#i am trying to display a particular product by clicking on it from the list

#i am trying this


<ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>

expected results should be poducts/1 but th result is products.1 and displays a list of products

dimanche 26 mai 2019

How to fetch api with javascript to display data?

I am trying to build an API with javascript to fetch data from this url for jason data: img, a, c . But below codes threw back an error of

application.js:10 Uncaught (in promise) TypeError: data.forEach is not a function

(why is the forEach method not defined) can you help? thanks

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/")
  .then(response => response.json())
  .then((data) => {

    data.forEach((result) => {

        const movies = '<li><img src="'+result.im+'" alt=""><h3>'+result.a+'</h3><p>'+result.c+'</p></li>';
        results.insertAdjacentHTML("beforeend", movies);

    });
  });


the Jason file:


{
      "a": "shoujo-apocalypse-adventure", 
      "c": [
        "Adventure", 
        "Drama", 
        "Psychological", 
        "Sci-fi", 
        "Seinen", 
        "Slice of Life", 
        "Tragedy"
      ], 
      "h": 156, 
      "i": "5c410d31719a16035a4647cc", 
      "im": "4a/4a1f2a595e0e84e62f6ceddf3946274478928ca99e8df86bc6511b6e.png", 
      "ld": 1547822837.0, 
      "s": 2, 
      "t": "Shoujo Apocalypse Adventure"
    }, 


samedi 25 mai 2019

Why does my paperclip configuration not work for?

I have a Photo model, I am running paperclip (>= 3.4.0), ruby 2.3.7, Rails 3.2.

In my photo.rb, I have the following:

class Photo < ActiveRecord::Base
  attr_accessible :position, :source_uri, :img, :published

  belongs_to :property

  has_attached_file :img,
    :styles => { :large => "590x380>", :medium => "380x200>", :small => "280x150>", :thumb => "100x75>" },
    :url => "#{:source_uri}" 

  def source_uri=(uri)
    self.img_file_name = "#{random_base_name}#{ext_from_mime}"
    super
  end

  def source_uri
    URI.unescape(super)
  end

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

  config.paperclip_defaults = {
    :storage => :s3,
    :bucket => ENV['MY_S3_BUCKET'],
    :path => "uploads/myapp/:class/:attachment/:id/:style/:filename",
    :s3_credentials => "#{Rails.root}/config/aws.yml",
    :default_url => ":attachment/:class/:style/missing.png"
  }

In my aws.yml, I have the following:

development:
  access_key_id:
  secret_access_key:
  bucket:

staging:
  access_key_id: <%= ENV["S3_ACCESS_KEY_ID"] %>
  secret_access_key: <%= ENV["S3_SECRET_ACCESS_KEY"] %>
  bucket: <%= ENV["S3_BUCKET"] %>

production:
  access_key_id: <%= ENV["MY_S3_ACCESS_KEY_ID"] %>
  secret_access_key: <%= ENV["MY_S3_SECRET_ACCESS_KEY"] %>
  bucket: <%= ENV["MY_S3_BUCKET"] %>

When I upload an image, it seems to work based on the logs:

  SQL (0.7ms)  INSERT INTO "photos" ("created_at", "featured", "img_content_type", "img_file_name", "img_file_size", "img_fingerprint", "img_updated_at", "position", "property_id", "published", "source_uri", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"  [["created_at", Sat, 25 May 2019 05:52:17 UTC +00:00], ["featured", nil], ["img_content_type", nil], ["img_file_name", "65798ASDASD4"], ["img_file_size", nil], ["img_fingerprint", nil], ["img_updated_at", nil], ["position", nil], ["property_id", 18713], ["published", true], ["source_uri", "https://s3-us-west-2.amazonaws.com/propbmedia/BenjaminJohnson/31680-1.jpg"], ["updated_at", Sat, 25 May 2019 05:52:17 UTC +00:00]]
   (0.9ms)  COMMIT

However, if I were to poke around in my console, I would get the following:

irb(main):027:0> q.photos.first.source_uri
  Photo Load (11.2ms)  SELECT "photos".* FROM "photos" WHERE "photos"."property_id" = 16759 ORDER BY position ASC LIMIT 1
=> "https://s3-us-west-2.amazonaws.com/propbmedia/BenjaminJohnson/10192-16.jpg"
irb(main):028:0> p.photos.first.source_uri
=> "https://s3-us-west-2.amazonaws.com/propbmedia/BenjaminJohnson/33449-7.jpg"
irb(main):029:0> q.photos.first.img.url
  Photo Load (8.2ms)  SELECT "photos".* FROM "photos" WHERE "photos"."property_id" = 16759 ORDER BY position ASC LIMIT 1
=> "http://s3.amazonaws.com/johnson-benjamin/uploads/hojo/photos/imgs/208532/original/9086718487708773"
irb(main):030:0> p.photos.first.img.url
=> "http://s3.amazonaws.com/johnson-benjamin/uploads/hojo/photos/imgs/241108/original/7782737090666986"

Note that the first two URLs in the last snippet work, but the last 2 return 'access denied' errors.

I also tried to upload an avatar to S3, using Comfy CMS and it worked. Granted, I don't think that is managed by Paperclip (I could be wrong), but for some reason it uploads it somewhere else. Here is an example URL for the avatar that works - http://s3.amazonaws.com/johnson-benjamin/uploads/hojo/agents/avatars/21/large/10PP-COMING-SOON.jpg?1558767320

So what could be wrong with my main property.photos model?

Why is that?

jeudi 23 mai 2019

how to display flex column with css when calling each method on the object

I am trying to display:flex columns on each item(product), but resulted in showcasing it in a vertical layout(codes as below), I was wondering how do i showcase it in displaying as flex and also when in an asymmetrical layout column(when looping through each object) as well. thank you!

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {
  box-sizing: border-box;
}

/* Create three equal columns that floats next to each other */
.column {
  display: flex;
  margin:20px;
  float: left;
  width: 33.33%;
  padding: 10px;
  height: 300px; /* Should be removed. Only for demonstration */
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}
</style>

</head>
<body>

<h2>All Products</h2>
<% @products.each do |product| %>



<div class="row">
  <div class="column" style="background-color:#aaa;">
    <%= product.product_name %>
    <%= product.description %>
  </div>


</div>
<% end %>
</body>
</html>

How to test private helper(module) method in rspec

I have a helper module named "AppHelper" and private method "sum" which I want to test using rspec.

For example:

module AppHelper
 private
 def sum(a,b)
   puts a+b
 end
end

Rails - Mongoid : Slow problem between production and development

I have a problem on my Rails application.

I am in version 3.2.22 of rails and 2.2.5 of ruby connect to a mongodb 2.6.

The problem is that I have huge difference in performance on simple or even more complex queries.

For example :

I run rails c development and then I execute my function (quite complex) it responds after 30 seconds I run rails c production, I perform the same function as the previous one, it responds after 6 minutes 30 seconds, 7 times slower. So I try to copy pasted the configuration 'development' in 'production', but the result remains the same, same for the Gemfile.

I look in all the code of the project no difference between the environment production and development.

Do you know the differences in the heart of rails between these two environments? did anyone ever encounter the problem?

Importantly, I am of course connecting to the same database.

Thanks in advance.

undefined method create product/ for nil class

There're two problems I encountered in the codes below, 1. I was trying to do @products.each do |product| but it threw me back undefined nill class on product - I've checked the problem in product controller but it's still not defined. 2. when I was trying to create a new product from the simple form for below but it doesn't seem to be saved into the db, is it because the devise issues?(it shows on the url link that authenticate token etc)this is what it shown in the url:http://localhost:3000/products/new?utf8=%E2%9C%93&authenticity_token=7L5t8CunwqhCGwaCs1L5BXG7WAFBxLE0kbpoDojXeE%2FzzUOPAXVZqXnFRw29OLPD2SsJ%2F%2FHm2EkT0q1qUvxYdQ%3D%3D&product%5Bproduct_name%5D=fvf&product%5Bcondition%5D=dfvd&product%5Bdescription%5D=vdfvdc&commit=Submit

class Product < ApplicationRecord
  belongs_to:user
  validates :product_name, presence: true, uniqueness: true

end

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many:products
    validates :name, presence: true, uniqueness: true

  def show

    @user = User.new

  end

end


class UsersController < ApplicationController



  def show

    @user = User.new

  end

end


  <div id='container'>
  <div class='signup_create_product'>
     <form>

<h1>Create a new product</h1>
      <%= simple_form_for @product do |f| %>
       <%= f.input :product_name,
                required: true,
                autofocus: true,
                input_html: { autocomplete: "product_name" }%>

   <%= f.input :condition,
                required: true,
                autofocus: true,
                input_html: { autocomplete: "condition" }%>

    <%= f.input :description,
                required: true,
                autofocus: true,
                input_html: { autocomplete: "description" }%>

         <div class="form-actions">
                <%= f.button :submit, "Submit" %>
              </div>
            <% end %>

     </form>
  </div>
  <div class='whysign'>
    <h1>Share your beloved products with all over the world!</h1>
    <p>This is an Airbnb style platform that you can create your own products and sell it or purchase from all over the world!</p>

    <i class="fas fa-home"></i><%= link_to 'home',root_path  %>


</div>

  </div>

class ApplicationController < ActionController::Base
  # [...]
  before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    # For additional fields in app/views/devise/registrations/new.html.erb
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])

    # For additional in app/views/devise/registrations/edit.html.erb
    devise_parameter_sanitizer.permit(:account_update, keys: [:username])
  end
end

class ProductsController < ApplicationController


  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create
    @product = Product.new(product_params)

    if @product.save
      redirect_to product_path(@product)
    else
      render :new
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def update
    @product = Product.find(params[:id])
    if @product.update(product_params)
      redirect_to product_path(@cocktail)
    else
      render :edit
    end
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to products_path
  end

  private

  def product_params
    params.require(:product).permit(:product_name, :description)
  end
end



mercredi 22 mai 2019

How to seed multiple items within same column?

I am trying to seed multiples items into the same column, i.e. 1 user with 5 products, but doesn't seem to work, I was wondering how do I do it? codes below


User.create!([{
  name: "Ant-Man",
  email: "1234@gmail.com",
  product: "mac","piano","paper","book",
  password: "123456",
},
{
  name: "Joe",
  email: "joe@gmail.com",
  product: "macboook",
  password: "123456",
},
{
  name: "Alice",
  email: "123@gmail.com",
  product: "mascara",
  password: "123456",
},
{
  name: "Amy",
  email: "amy@gmail.com",
  product: "travelling book",
  password: "123456",
},
{
  name: "James",
  email: "James@gmail.com",
  product: "pen",
  password: "123456",
},
{
  name: "Edward",
  email: "edward@gmail.com",
  product: "piano",
  password: "123456",
},])

Slow problem between production and development rails console

I have a problem on my Rails application.

I am in version 3.2.22 of rails and 2.2.5 of ruby connect to a mongodb 2.6.

The problem is that I have huge difference in performance on simple or even more complex queries.

For example :

  • I run 'rails c development' and then I execute my function (quite complex) it responds after 30 seconds
  • I run 'rails c production', I perform the same function as the previous one, it responds after 6 minutes 30.

So I try to copy pasted the configuration 'development' in 'production', but the result remains the same, same for the Gemfile.

I look in all the code of the project no difference between the environement production and development.

Do you know the differences in the heart of rails between these two environments? did anyone ever encounter the problem?

Importantly, I am of course connecting to the same database.

Thanks in advance.

How can I access a constant defined in one initializer file into another initializer file in rails?

I have defined a YAML file like this throttling_request.yml

logged_in_user:
  watching_timespan: 60
  allowed_requests:  60
  blocking_timespan: 300

non_logged_in_user:
  watching_timespan: 300
  allowed_requests:  300

I load the YML file in config/intializers/throttle_config.rb

config = YAML.load_file('config/throttling_request.yml').with_indifferent_access
THROTTLE_REQ_NON_LOGGED_IN = config[:non_logged_in_user]
THROTTLE_REQ_LOGGED_IN     = config[:logged_in_user]


But I want to access this constant THROTTLE_REQ_NON_LOGGED_IN into another initializer file config/initializers/rack_attack.rb

  configs = ::THROTTLE_REQ_NON_LOGGED_IN

  # Throttle all requests by IP (20rpm)
  #
  # Key: "rack::attack:#{Time.now.to_i/:period}:req/ip:#{req.ip}"
  throttle('req/ip', limit: configs[:allowed_requests], period: configs[:watching_timespan]) do |req|
    req.ip unless req.path.start_with?('/assets')
  end

I could not able to load with or without scope resolution operator :: for constant THROTTLE_REQ_NON_LOGGED_IN. I want to use constants THROTTLE_REQ_LOGGED_IN for my other class and THROTTLE_REQ_NON_LOGGED_IN in rack attack config. So I don't want to mix up calling this constant in rack attack initializer file.

Please let me know if any other information needed from me.

Has_many :through association using 3 models

I have 3 models teacher, student, subject. I want to get the list of Students handled by the teacher in a particular subject and in params for subject I want to provide subject_name. how can I do it using has_many :through association? thanks in advance

lundi 20 mai 2019

Please how can i edit this simple script to send an attachment. using ruby mail

Using Mail I am able to send messages (HTML) perfectly using this script email_handler.rb on Ruby, please how can i add an attachment (eg pdf) to my message, i have tried it for 2 weeks now, please i need help guys please. Here goes the email handler scipt below.

"""
Author: daemon
Description: Module to send bulk emails using any email address, with functional programming
"""

require './savmail/lib/mail.rb'

require './utils.rb'

RECIPIENT_HOLDER = "%0%"

module EmailHandler
    def self.format_email(email: '', recipient: '')
        # fill in all the placeholders
        return email.gsub(RECIPIENT_HOLDER, recipient)
    end


    def self.compose_email(recipient: nil, sender: nil, sender_name: nil, subject: '', html: nil, text: '')
        # Save recipient so other threads don't touch
        Utils.save_recipient(email: recipient)
        text_content = text
        html_content = format_email(email: html, recipient: recipient)

        mail = Mail.new do
            to      recipient
            from    sender_name + " <" + sender + ">"
            subject subject
        end

        text_part = Mail::Part.new do
            body text_content
        end

        html_part = Mail::Part.new do
            content_type 'text/html; charset=UTF-8'
            body html_content
        end

        mail.text_part = text_part
        mail.html_part = html_part

        return { 'msg'=> mail, 'recipient'=> recipient, 'sender'=> sender }
    end

    def self.email_login(sender_tuple: [], mail: '')
        smtp_login = sender_tuple[0]
        smtp_password = sender_tuple[1]
        smtp_host = sender_tuple[2]
        smtp_port = sender_tuple[3]
        limit = sender_tuple[4]

        begin
            # server = smtplib.SMTP(smtp_host, smtp_port)
            # server.starttls()
            # server.login(smtp_login, smtp_password)
            options = { 
                :address              => smtp_host,
                :port                 => smtp_port,
                # :domain               => 'your.host.name',
                :user_name            => smtp_login,
                :password             => smtp_password,
                :authentication       => 'login',
                # :enable_starttls_auto => true  
            }
            mail.delivery_method :smtp, options

            return mail
        rescue Exception => e
            puts 'Failed to Login to ' + smtp_login
            return false
        end
    end

    def self.send_email(payload: nil, sender_address: nil, recipient: nil, server: nil)
        begin
            payload.deliver
            puts 'Sent from '+sender_address+' to '+recipient
            return payload
        rescue Exception => e
            Utils.save_recipient(email: recipient, failed: true)
            puts 'Email Failed to Send from '+sender_address+' to '+ recipient
            return false
        end
    end
end

and this is the main script (main.rb) that handles initiates the sending sequence once you enter it in the cmd prompt..

"""
Author: daemon
Description: Send bulk emails using any email address
"""

# from email_handler import compose_email, send_email, email_login
require './email_handler.rb'
require './utils.rb'
include EmailHandler

# Change Subject for all emails here
$custom_sender_name = "MAIL@MAIL.COM"
$custom_sender_email = "no-reply.#randstring@MAIL.COM"
$email_subject = "TEST"
$threads_total = 10

# These files have to exist
$army_file_path = './army.txt'
$email_file_path = './msg.html'
$senders_file_path = './senders.txt'


def mail_savage(recipients, senders, payload, custom_sender_email, custom_sender_name, email_subject, active_limit: nil, active_server: nil)
    ''' Login as one sender and send emails until the limit is reached or the email stops working,
    then do the same for the rest
    '''
    # Get first recipient from array
    sender = senders[0]

    # sender_email, smtp_password, smtp_host, smtp_port, limit = sender
    sender_email = sender[0]
    smtp_password = sender[1]
    smtp_host = sender[2]
    smtp_port = sender[3]
    limit = sender[4]
    mail_limit = active_limit or limit.to_i

    # if !recipients
    #     return true
    # end

    # Make sure we haven't emailed this user before
    for recipient in recipients
        if Utils.is_recipient_saved(email: recipient)
            # Move to next email if sent already
            next
        end

        # compose email
        # mail, recipient_email, csender_email = compose_email(recipient=recipient, sender=sender_email, sender_name=custom_sender_name, subject=email_subject, html=payload)
        mail_data = EmailHandler.compose_email(recipient: recipient, sender: sender_email, sender_name: custom_sender_name, subject: email_subject, html: payload)
        mail = mail_data['msg']
        recipient_email = mail_data['recipient']
        csender_email = mail_data['sender']


        # Login as sender if fail dump sender
        server = false
        while server == false do
            server = EmailHandler.email_login(sender_tuple: sender, mail: mail)
        end

        # Send email
        # print('Sending from %s to %s' % (sender_email, recipient))
        if !EmailHandler.send_email(payload: server, sender_address: sender_email, recipient: recipient_email, server: server)
            # email failed to send
            # Call it again without this sender and with the current limit
            server = EmailHandler.email_login(sender_tuple: sender, mail: server)
        end
    end

    # if server
    #     server.finish
    # end
    return true
end


def main()
    ''' Send email from msg.html to all addresses in army.txt
    with the addresses in senders.txt
    '''

    senders_all = Utils.get_sender_addresses(path: $senders_file_path)
    recipients_all = Utils.get_army_addresses(path: $army_file_path)
    html_content = Utils.get_email_content(path: $email_file_path)

    threads = []

    for th in 0..$threads_total-1
        threc = recipients_all[th..recipients_all.length-1]

        if threc != nil && threc.length > 0

            threads << Thread.new {
                if th == 0
                    sleep 2
                end
                mail_savage(recipients_all, senders_all, html_content, $custom_sender_email, $custom_sender_name, $email_subject, active_limit: nil, active_server: nil)
            }
        end
        # thread.join
        # thread.start()
    end

    threads.each do |t|
        t.join
    end
end

main


this scripts works fine and sends out html messages perfectly as of now.

PLEASE HOW CAN I EDIT THIS SCRIPTS TO SEND AN ATTACHMENT? e.g pdf I HAVE TRIED EVERYTHING I KNOW, very important to me, please help me guys, Wish you goodluck in all you do! P/S: I'm new to Ruby, please be kind

Fcm gem not working for ruby 1.9.3, Any alternative to implement fcm based push notifications

Currently we are using "gcm" gem to send push notifications from rails server to android and ios apps. Now we need to update gcm to fcm. When I tried to use "fcm" gem getting error "required ruby version above 2.0.0" while bundle install. can any one please help me any alternate solution to implement fcm based push notifications in ruby on rails. Our project ruby version 1.9.3 and rails 3.2.10.

Thanks in advance...

How to open a file with with ruby?

I am trying to open a file on rails user model with ruby and call it from user controller but it kept throwing me back wrong number of arguments (given 0, expected 1..3).

This is my file directory 'app' ,'assets', 'files', 'test_list.txt' 'app' ,'controllers', 'users controller'

can you help?thanks

class User < ApplicationRecord


  def self.my_method


    my_array = []


    file = File.join(Rails.root, 'app' 'models','assets', 'files', 'test_list.txt')
    File.open.each do  |line|

    my_array << line.gsub!(/\n?/, "")



    end

    return my_array.to_s

    end


end

class UsersController < ApplicationController

  require 'open-uri'
  require 'net/http'


  def show

    # uri = URI('https://gist.githubusercontent.com/Kalagan/3b26be21cbf65b62cf05ab549433314e/raw')
    #   data = Net::HTTP.get(uri)
    #   anagrams = data.split(/\n/)


    @vari = User.my_method
    @query = params[:query]
    @results = anagrams.select { |word| @query.split('').sort.join == word.split('').sort.join }



  end


end




samedi 18 mai 2019

How to pass the params to two different tables in rails

As a newbie I started to do API POC. I have a situation as explained below:

I have seekerController which has create method.I want that when a Post request makes then few parameters has to go seeker table and few needs to go profile table(This table also have the seekerID column). I want to do this with in Transaction commit. So after reading I started doing below:-

ActiveRecord::Base.transaction do
          seeker = Seeker.new(seeker_params)
          seeker.save!
          params[:seeker_id] = seeker[:id]

          seekerprofile = SeekerProfile.new(seekerprofile_params)
          seekerprofile.save!
          end
      render json: {status: 'success', message: 'Request is processed successully', data:seeker},status: :created;

I have below definition:(I have doubt i the below way is correct)

def seeker_params
    params.require(:seeker).permit(:username, :alias, :mobile_number, :country_code, :email_address, :description, :status)
  end
  def seekerprofile_params
    params.require(:seeker_profile).permit(:seeker_id, :first_name, :middle_name, :last_name, :date_of_birth, :pincode, :building_name, :address, :email_address, :description, :status)

  end

its not working. I am not finding way to do it.also how to prepare seeker_params and seekerprofile_params.

jeudi 16 mai 2019

How to push into arrays when reading ruby files?

I've followed the tutorial about how to read a text file with ruby with the purposes of printing it out with arrays, but it doesn't seem like working... here are the attempts in test.rb.

tutorial:https://www.codecademy.com/articles/writing-to-file-ruby

this test list file is successfully printing put in the console but its not in an array, how do I turn it into array? thanks!

test.rb 
class File
File.open("test_list.txt").each do  |line|

puts line
def ProcessText
    test_list.txt = File.to_s

end
end
end 

Reorganize array of hashes

have array of hashes it looks like

arr = [
  {"partner_name"=>"Bell", "publisher_name"=>"News - Calgary", "mn"=>"", "mid"=>415},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Vancouver Island", "mn"=>"Module 2.0 ", "mid"=>4528},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Atlantic", "mn"=>"Module 2.0 ", "mid"=>4531},
  {"partner_name"=>"Bell", "publisher_name"=>"News - Kitchener", "mn"=>"Module 2.0 ", "mid"=>4535},
  {"partner_name"=>"Bell", "publisher_name"=>"News - London", "mn"=>"Module 2.0 ", "mid"=>4536},

]

i have tried to do arr.group_by{|el|el['partner_name']}

i want to achieve this result

{
  partner:'Bell',
  publishers: [
    {name:'News - Vancouver Island'},
   modules:[
    {mn: val, mid: id_val},
    # ...
    {name:'News - Vancouver Island'
     modules:[
    {mn: val, mid: id_val},
    # ...
   ],},
    # ... and others
  ],
}

How can i do it?

mercredi 15 mai 2019

How do I set up my rails application to be able to receive an HTTP GET request with the requested word as the path and return the results as JSON

How to set up my rails application to be able to receive an HTTP GET request with the requested word as the path and return the results as JSON. codes as follow;

GET --> http:://{url}?search={username}

I need to return

GET /crepitus 
{"crepitus":["cuprites","pictures","piecrust"]} 
GET /crepitus,paste,kinship,enlist,boaster,fresher,sinks,knits,sort 
{"crepitus":["cuprites","pictures","piecrust"],"paste":["pates","peats","septa","spate","tapes","tepas "],"kinship":["pinkish"],"enlist":["elints","inlets","listen","silent","tinsel"],"boaster":["boaters","borate s","rebatos","sorbate"],"fresher":["refresh"],"sinks":["skins"],"knits":["skint","stink","tinks"],"sort":["o rts","rots","stor","tors"]}\ GET /sdfwehrtgegfg 
{"sdfwehrtgegfg":[]} 


and the application should be able to respond to a request made every second, should I set in on the Heroku side?

mardi 14 mai 2019

How to hold the checkbox true value in rails after search

The search is working fine but the problem is that when i print the excel report according to the result.it is showing all the values in the database, filter is not working then Checkbox true values are gone. How to hold the 'All address' checkbox params after refreshing the page.

This is my view

.col-md-3.small_scale_margin-top2
  = check_box_tag "all_address"
  = label_tag "Show All Addresses"

This is my controller

    if params[:search].present? or params[:excel_report].present?

      search_customer_supplier = params[:search_customer_supplier]

      if params[:organization_children].present? and search_customer_supplier["id"].present?
        organization_id = search_customer_supplier["id"]
        organization = Organization.find(organization_id)
        anchestor_ids = organization.anchestors.map{|o| o[:member].id }
        search_customer_supplier["id"] = "(#{anchestor_ids.join(' OR ')})" if anchestor_ids.any?
      end
      #puts "======================================================================"
      # puts params[:search_customer_supplier]['accounts_dealer_types.dealer_code']

      params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] = params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].join(" OR ") if params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].present?

      # puts params[:search_customer_supplier]['accounts_dealer_types.dealer_code']

      customer_report = params[:search_customer_supplier].map { |k, v| "#{k}:#{v}" if v.present? }.compact
    else
      customer_report = ["accounts_dealer_types.dealer_code:(CUS OR SUP OR INDCUS OR INDSUP)"]
    end

    @all_address = params[:all_address].to_bool if params[:all_address].present?
    refined_query += customer_report.join(" AND ")
    params[:query] = refined_query
    # params[:per_page] = 500
    @customer_reports = Organization.search(params)

    puts "========================================================="
      puts @customer_reports
    puts "========================================================="

    @account_managers = User.where(active: true)
    respond_to do |format|
      if params[:excel_report].present?
        request.format = "xls"
        format.xls { set_attachment_name "customer_supplier_report.xls" }
      else
        format.html
      end
    end

  end

In my controller this is the relevant part for the checkbox

@all_address = params[:all_address].to_bool if params[:all_address].present?

How to get column name for primary_key at database level?

I need to get the column name containing the primary key(s) at the database level.

Model.primary_key returns models_id column name which is not the primary key at the database level. I cannot change migrations or modify the tables in anyway.

I can currently get it through the MySqlAdapter with ActiveRecord::Base.connection.primary_key('table_name')

but this does not work with tables that have composite primary keys. If the table contains a composite primary key it returns nil.

Is there any way I can achieve this programatically?

How to hold the checkbox params in rails after search

The search is working fine but the problem is that when i print the excel report according to the result.it is showing all the values in the database, filter is not working.Realoding all over the page, then Checkbox true values are gone. How to hold the params after refreshing the page

   .row
            .col-md-3
              = check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]","CUS", false
              = label_tag "Organizational Customer"
            .col-md-3
              = check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "SUP", false, class: "first_resolution"
              = label_tag "Organzational Supplier"
            .col-md-3
              = check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "INDCUS", false, class: "first_resolution"
              = label_tag "Individual Customer"
            .col-md-3
              = check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "INDSUP", false, class: "first_resolution"
              = label_tag "Individual Supplier"

This is my controller,

    if params[:search].present? or params[:excel_report].present?

      search_customer_supplier = params[:search_customer_supplier]
      if params[:organization_children].present? and search_customer_supplier["id"].present?
        organization_id = search_customer_supplier["id"]
        organization = Organization.find(organization_id)
        anchestor_ids = organization.anchestors.map{|o| o[:member].id }
        search_customer_supplier["id"] = "(#{anchestor_ids.join(' OR ')})" if anchestor_ids.any?
      end
      params[:search_customer_supplier]['accounts_dealer_types.dealer_code'] = params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].join(" OR ") if params[:search_customer_supplier]['accounts_dealer_types.dealer_code'].present?

      @all_address = params[:all_address].to_bool if params[:all_address].present?
      customer_report = params[:search_customer_supplier].map { |k, v| "#{k}:#{v}" if v.present? }.compact
    else
      customer_report = ["accounts_dealer_types.dealer_code:(CUS OR SUP OR INDCUS OR INDSUP)"]
    end

How to hold the checkbox params in rails after search

The search is working fine but the problem is that when i print the excel report according to the result.it is showing all the values in the database, filter is not working. Reloading all over the page, then Checkbox true values are gone. How to hold the params after refreshing the page

In my view,

.col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]","CUS", false
= label_tag "Organizational Customer"
.col-md-3
=check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "SUP", false, class: "first_resolution"
= label_tag "Organzational Supplier"
.col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "INDCUS", false, class: "first_resolution"
= label_tag "Individual Customer"
.col-md-3
= check_box_tag "search_customer_supplier[accounts_dealer_types.dealer_code][]", "INDSUP", false, class: "first_resolution"
= label_tag "Individual Supplier"

How can I set the user_type in the mailboxer_notifications table?

My problem is that when users reply to each other, it's hard examine the database via SQL and differentiate between user types (so admin, and individual users). The default is just "User", as a string.

When examining the mailboxer code, I know it calls the "reply" method in the Conversations controller. This is the relevant part of the code:

def reply
  current_user.reply_to_conversation(conversation, message_params[:body])
  flash[:notice] = "Message was sent."
  redirect_to conversation_path(conversation)
end

From this, I wanted to do something like:

conversation.messages.sender_type = params[:custom].present? ? params[:custom] : "Admin"

But this does not work, as it says "unknown sender type method". I listed it that way because, based on the mail boxer gem code, messages belongs_to conversation, and the messages model is linked to the table and column value I want to change.

This is the relevant code: https://github.com/mailboxer/mailboxer/blob/03543e8a06dea8c9bfb52963da8abbf1157d5d21/app/models/mailboxer/message.rb

Based on this, what should I modify to have it so when I reply to a user, the reply action is called, and then conversations "calls" messages which itself sets the sender_type to a value I want?

lundi 13 mai 2019

How to get class instance variable into module

I am unable to overwrite the module variable by class instance variable.

module Main
 class Traks
   @@endpoint ='/trakings'
   class << self
     include ViewTrait
   end
 end 

end

My Trait Module

module Main
 module ViewTrait
      def view(id:, options: "")
        Response::new("#{@@endpoint}/#{id}#{options}").resource(id: id).get
      end
    end
end

in ViewTrait I cannot access @@endponint which I have already defined in my Traks class. anyone can let me what I went wrong.

ActionController::RoutingError: No route matches [POST] \"/seekers\

Hi I am relatively new to Rails framework. I started doing a POC. I am stuck into strange problem.

My routes.rb has below:

resources :seekers, only: [ :index, :show, :create ]

My seekers_controller has below code

class SeekersController < ApplicationController
def create
    #byebug
"some code"
end
end

it was working earlier, i was trying to add another controller resource with same functionality , then realized its not working. Then I reverted back the code just test it, and found the old code is also not working. for every thing it just throws the below error:-

ActionController::RoutingError (No route matches [POST] "/seekers"):

My rail routes gives me correct as below path:

 POST  /seekers(.:format)
            seekers#create
 GET   /seekers/:id(.:format)

The Rest Url which i am using as below

http://localhost:3000/seekers

Don't know what is wrong. everything was working fine earlier. I have tried to changing the routes.rb by multiple way but nothing works.

Appreciate help on this !!!

version details as below: ruby '2.3.3' gem 'rails', '~> 5.2.2', '>= 5.2.2.1'

Performance difference in Concern method ran with Hook vs on Model?

Basically I notice a big performance difference in dynamically overriding a getter for ActiveRecord::Base models within an after_initialize hook and simply within the model itself.

Say I have the following Concern:

Module Greeter
  extend ActiveSupport::Concern

  included do
    after_initialize { override_get_greeting }
  end

  def override_get_greeting
    self.class::COLS.each do |attr|
      self.class.class_eval do
        define_method attr do
          "Hello #{self[attr]}!"
        end
      end
    end
  end

end

I then have the following model, consisting of a table with names.

CREATE TABLE 'names' ( 'name' varchar(10) );
INSERT INTO names (name) VALUES ("John")

class Name < ActiveRecord::Base
  COLS = 'name' 
  include Greeter
end

john = Name.where(name: 'John').first
john.name # Hello John!

This works fine. However, if I try to do this a more Rails way it is significantly slower.

Essentially, I want to simply pass a parameter into Greeter method that contains COLS and then overrides the getters. It'll look something like:

# Greeter
Module Greeter
  extend ActiveSupport::Concern

  def override_get_greeting(cols)
    cols.each do |attr|
      self.class.class_eval do
        define_method attr do
          "Hello #{self[attr]}!"
        end
      end
    end
  end

end

# Name
class Name < ActiveRecord::Base
  include Greeter
  override_get_greeting :[name]
end

Now Name.where(name: 'John').first.name # Hello John! is about 2 seconds slower on the first call.

I can't put my finger in it. I have an assumption that the the application is just slower to start with the first example, but not really sure.

I prefer the second example but the performance difference is a big no no.

Has anyone came across something like this?

vendredi 10 mai 2019

can someone please explain about api concept here in ruby on rails?

can someone please explain to me about this?

render json: {
      error: "Unauthorized #{exception.policy.class.to_s.underscore.camelize}.#{exception.query}"
    }, status: :unauthorized

and the exception part, thanks.

class Api::V1::BaseController < ActionController::API
  include Pundit

  after_action :verify_authorized, except: :index
  after_action :verify_policy_scoped, only: :index

  rescue_from StandardError,                with: :internal_server_error
  rescue_from Pundit::NotAuthorizedError,   with: :user_not_authorized
  rescue_from ActiveRecord::RecordNotFound, with: :not_found

  private

  def user_not_authorized(exception)
    render json: {
      error: "Unauthorized #{exception.policy.class.to_s.underscore.camelize}.#{exception.query}"
    }, status: :unauthorized
  end

  def not_found(exception)
    render json: { error: exception.message }, status: :not_found
  end

  def internal_server_error(exception)
    if Rails.env.development?
      response = { type: exception.class.to_s, message: exception.message, backtrace: exception.backtrace }
    else
      response = { error: "Internal Server Error" }
    end
    render json: response, status: :internal_server_error
  end
end

Can someone explain to me about the are the cases when using before_action in rails?

1.can someone please explain to me what these lines do below and what are the cases to use before_action? 2.what does policy_scope here do?

class QuestionsController < ApplicationController
  skip_before_action :authenticate_user!, only: [:index, :show]
end

def index
  if params[:query].present?
  @questions = policy_scope(Question).where(category_id: params[:query])
  else
  @questions = policy_scope(Question)
   end
 end

jeudi 9 mai 2019

Model.where() with multiple params with check if they are present in rails

I am new to rails. I started working on a POC.

My Controller code is below:

> @xyz = if params[:id].present?
>                   if params[:mobile_number].present?
>                     Seeker.where("id = ? and mobile_number = ?" , params[:id], params[:mobile_number])
>                     
>                   else
>                    
>                     Seeker.where("id = ?", params[:id])
>                 end
>               elsif params[:seekerid].present?
>                   Seeker.where("mobile_number = ?" , params[:mobile_number])
>               else
>                 Seeker.where(nil);
>               end

But I don't think so Its good approach. Consider If i have many parameter then Putting present? condition then forming query would become complex. or can i form a query separately then place it into where condition as instance variable. what is the better approach?

mercredi 8 mai 2019

Unable to save a record with has many through relationship rails

i m trying to save a model which has a has_mnay through relationship with another model, unforunately it dosent allow to save let me explain

class Group < ActiveRecord::Base
  has_many :group_members, inverse_of: :group
  has_many :members, through: :group_members
end

class GroupMember < ActiveRecord::Base
  belongs_to :group
  belongs_to :member

  validates_presence_of :group, :member
end

class Member < ActiveRecord::Base
  has_many :group_members, inverse_of: :member
  has_many :groups, through: :group_members

 validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: true

end


so in my console i create a group

g = Group.last.dup (duplicating a record)
m = Member.last
g.members << m
g.save!

i get this error

ActiveRecord :: RecordInvalid: Authentication went wrong: Members email is already used,

note that i just have only one member in database i dont what else needs to be done, i have been trying this for the past one day, i cant find a solution for this

How to use "POST url" JSON file in RoR website?

I am using Ruby on Rails and Kibana to show visualisation in my website(Ruby2.6.0, Rails5.2.3, Kibana6.6.1). By using Xpack->Share->Generate PDF/PNG, I find 'copy POST url'. I can get the following JSON file from the POST url by python script, but how can I use POST url in my RoR website to show visualisation PNG file for users? To download PDG file in 'assets' folder?

JSON file from POST url: {'path': '/api/reporting/jobs/download/jvds4zs10qv79d0062b9cel6', 'job': {'id': 'jvds4zs10qv79d0062b9cel6', 'index': '.reporting-2019.05.05', 'type': 'esqueue', 'jobtype': 'PNG', 'created_by': False, 'payload': {'type': 'visualization', 'title': '[eCommerce] Sales by Gender', 'relativeUrl': "/app/kibana#/visualize/edit/ed8436b0-b88b-11e8-a6d9-e546fe2bba5f?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-60d,mode:quick,to:now))&_a=(filters:!(),linked:!f,query:(language:lucene,query:''),uiState:(),vis:(aggs:!((enabled:!t,id:'1',params:(),schema:metric,type:count),(enabled:!t,id:'2',params:(field:customer_gender,json:'',missingBucket:!f,missingBucketLabel:Missing,order:desc,orderBy:'1',otherBucket:!f,otherBucketLabel:Other,size:5),schema:segment,type:terms)),params:(addLegend:!t,addTooltip:!t,isDonut:!t,labels:(last_level:!t,show:!t,truncate:100,values:!t),legendPosition:right,type:pie),title:'%5BeCommerce%5D+Sales+by+Gender',type:pie))", 'headers': 'uxY4w6gCRwwLZyFkDX0ujVlANYq7ae5UuNJAN0GpbTOX7vw5aPuCuyr37nNcpz3vtA8kNVaL6Gacs24mPjZfwl4mB9xRKGA62CkCLo8Xz1amuIEthI+BtKPGo5QAk2k2+7zLvLgX3KouVvYdd61U5rLAvfjv4TydcpH9qJ4qrL5OELkzAJGrNdujtDLWaoy2Qj9YXbLnh7gSdI+lrNml6usZIh4pMzz8qdRo597iO/4AeSJRa2JfAruyGB3zYInZRtMuCbA4f3ANvT2WeAn6lpiwThB993uEjwu4LBVUZuo2XL0TcB29YNNa9oMCUEhWjdJ1ase5VQdz8V2IOgecQ1W52V5JuVTvl9SkVvFWSBhXJg==', 'browserTimezone': 'Europe/Zurich', 'layout': {'dimensions': {'height': 589.234375, 'width': 866}}, 'basePath': '', 'forceNow': '2019-05-07T12:38:12.768Z'}, 'timeout': 120000, 'max_attempts': 3, 'priority': 10, 'browser_type': 'chromium'}}

I am trying to use 'net/http', What I added in controller:

class MaisonController < ApplicationController

require 'net/http'

def require_post
    uri = URI.parse("http://localhost:5601/api/reporting/generate/png?jobParams=(browserTimezone:Europe%2FZurich,layout:(dimensions:(height:589.234375,width:866)),objectType:visualization,relativeUrl:%27%2Fapp%2Fkibana%23%2Fvisualize%2Fedit%2Fed8436b0-b88b-11e8-a6d9-e546fe2bba5f%3F_g%3D(refreshInterval:(pause:!!t,value:0),time:(from:now-60d,mode:quick,to:now))%26_a%3D(filters:!!(),linked:!!f,query:(language:lucene,query:!%27!%27),uiState:(),vis:(aggs:!!((enabled:!!t,id:!%271!%27,params:(),schema:metric,type:count),(enabled:!!t,id:!%272!%27,params:(field:customer_gender,json:!%27!%27,missingBucket:!!f,missingBucketLabel:Missing,order:desc,orderBy:!%271!%27,otherBucket:!!f,otherBucketLabel:Other,size:5),schema:segment,type:terms)),params:(addLegend:!!t,addTooltip:!!t,isDonut:!!t,labels:(last_level:!!t,show:!!t,truncate:100,values:!!t),legendPosition:right,type:pie),title:!%27%255BeCommerce%255D%2BSales%2Bby%2BGender!%27,type:pie))%27,title:%27%5BeCommerce%5D%20Sales%20by%20Gender%27)")
    http = Net::HTTP.new(uri.host,uri.port)

    request = Net::HTTP::Post.new(uri.request_uri)
    response = http.request(request)
    render :json => response.body
end
end

mardi 7 mai 2019

Nginx / Passenger Standalone / nginx-config-template / Rails3

The route is found and on the next reload, it is not found. Is there a config that I'm missing that could be causing this?

The strange thing is, it is 1:1 on the error and success of the route being found. It's not intermittent but errors and succeeds with each reload.

It's been 5 days and thought I'd ask the community for any suggestions.

ActionController::RoutingError (No route matches [GET] "/tools/auth/select"):
  vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22.4/lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22.4/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
  vendor/bundle/ruby/2.2.0/gems/railties-3.2.22.4/lib/rails/rack/logger.rb:32:in `call_app'
  vendor/bundle/ruby/2.2.0/gems/railties-3.2.22.4/lib/rails/rack/logger.rb:16:in `block in call'
  vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22.4/lib/active_support/tagged_logging.rb:22:in `tagged'
  vendor/bundle/ruby/2.2.0/gems/railties-3.2.22.4/lib/rails/rack/logger.rb:16:in `call'
  vendor/bundle/ruby/2.2.0/gems/quiet_assets-1.0.3/lib/quiet_assets.rb:23:in `call_with_quiet_assets'
  vendor/bundle/ruby/2.2.0/gems/actionpack-3.2.22.4/lib/action_dispatch/middleware/request_id.rb:22:in `call'
  vendor/bundle/ruby/2.2.0/gems/rack-1.4.7/lib/rack/methodoverride.rb:21:in `call'
  vendor/bundle/ruby/2.2.0/gems/rack-1.4.7/lib/rack/runtime.rb:17:in `call'
  vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22.4/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  vendor/bundle/ruby/2.2.0/gems/rack-1.4.7/lib/rack/lock.rb:15:in `call'
  vendor/bundle/ruby/2.2.0/gems/rack-cache-1.6.1/lib/rack/cache/context.rb:140:in `forward'
  vendor/bundle/ruby/2.2.0/gems/rack-cache-1.6.1/lib/rack/cache/context.rb:249:in `fetch'
  vendor/bundle/ruby/2.2.0/gems/rack-cache-1.6.1/lib/rack/cache/context.rb:189:in `lookup'
  vendor/bundle/ruby/2.2.0/gems/rack-cache-1.6.1/lib/rack/cache/context.rb:66:in `call!'
  vendor/bundle/ruby/2.2.0/gems/rack-cache-1.6.1/lib/rack/cache/context.rb:51:in `call'
  vendor/bundle/ruby/2.2.0/gems/railties-3.2.22.4/lib/rails/engine.rb:484:in `call'
  vendor/bundle/ruby/2.2.0/gems/railties-3.2.22.4/lib/rails/application.rb:231:in `call'
  vendor/bundle/ruby/2.2.0/gems/railties-3.2.22.4/lib/rails/railtie/configurable.rb:30:in `method_missing'
  passenger (6.0.2) src/ruby_supportlib/phusion_passenger/rack/thread_handler_extension.rb:97:in `process_request'
  passenger (6.0.2) src/ruby_supportlib/phusion_passenger/request_handler/thread_handler.rb:149:in `accept_and_process_next_request'
  passenger (6.0.2) src/ruby_supportlib/phusion_passenger/request_handler/thread_handler.rb:110:in `main_loop'
  passenger (6.0.2) src/ruby_supportlib/phusion_passenger/request_handler.rb:415:in `block (3 levels) in start_threads'
  passenger (6.0.2) src/ruby_supportlib/phusion_passenger/utils.rb:113:in `block in create_thread_and_abort_on_exception'


Started GET "/tools/auth/select" for 57.130.176.32 at 2019-05-07 15:04:13 -0700
Processing by AuthController#select as HTML
  Rendered auth/select.html.erb within layouts/external_views (0.0ms)
Completed 200 OK in 5496.3ms (Views: 4.0ms | ActiveRecord: 0.0ms)

Click event works in incognito but not in normal chrome

I have a vue application where I have signup up page for onboarding customers. There is a click event on an action button after filling all the details it proceeds further.But that button is working fine in incognito but not in normal chrome What is the root cause of such problem and how can I fix it ?

lundi 6 mai 2019

Ruby HATBM - Negative Filtering behaving strange

Lets imaging looking at a ruby schema with two resources (user & books) which have an HABTM association.

When I am filtering based on this association, whether a user has a book or not, ruby behaves a bit strange:

2.5.3 :007 > Contact.includes(:books).count
(4.7ms)  SELECT COUNT(*) FROM "contacts"
=> 36880 

Which is fine, because it returns the total value of contacts with any book association.

2.5.3 :010 > Contact.includes(:books).where(books: {"id":[1,2] }).count
   (34.0ms)  SELECT COUNT(DISTINCT "contacts"."id") FROM "contacts" LEFT OUTER JOIN "contacts_books" ON "contacts_books"."contact_id" = "contacts"."id" LEFT OUTER JOIN "contacts" ON "contacts"."id" = "contacts_books"."book_id" WHERE "books"."id" IN (?, ?)  [["id", 1], ["id", 2]]
 => 24864 

Which is also fine, since it returns all contacts which have book with id 1 or 2.

2.5.3 :011 > Contact.includes(:books).where.not(books: {"id":[1,2] }).count
   (13.0ms)  SELECT COUNT(DISTINCT "contacts"."id") FROM "contacts" LEFT OUTER JOIN "contacts_books" ON "contacts_books"."firm_id" = "contacts"."id" LEFT OUTER JOIN "contacts" ON "books"."id" = "contacts_books"."book_id" WHERE "books"."id" NOT IN (?, ?)  [["id", 1], ["id", 2]]
 => 0 

Now this part doesnt make sense, because it should be total - #associations, so 36880 - 24864 leaving me with 12016 records and not 0.

Or what am I missing?

How to use correctly def with if..else statements in ruby?

I started learning ruby, for this moment I understand how to create class objects, and how to write very simple IF..ELSE statement. But how to write correctly def with IF..ELSE statement? Help please with advice how to write it correctly?

   #I can write simple statement like this 

number = 1
if number == 1
    number += 1
    puts "the number is #{number}"
else 
    puts "number is more then 2"
end

#But then i want to write something like this 

class Maths
  def initialize(number_id)
    @number = number_id 
  end 
    def numberdata()
      if @number == 1 
         @number +=1
      puts "the number is #@number"
    else 
      puts "number is greater than 3"
   end
  end
end
   classob5 = Maths.new("1")
   classob5.numberdata()`

I expected the outout from the second part like this "the number is 2", but actual is "number is greater than 3" Help please with advice how to write it correctly

dimanche 5 mai 2019

React not passing authorization header to rails api

I am using React frontend with a graphql rails api backend for a SaaS project with apartment. I need to get the authorization token from request.env so i can decode the user_id to get the tenant name which is a field in the User model. This is for a generic elevator based on the user logged in. When i inspect the Rails logger log I see that "HTTP_AUTHORIZATION"=>"" it's empty. what did i go wrong.

This is from the index.js where the authorization is added:

    const authLink = setContext((_, { headers }) => {
      const token = localStorage.getItem(AUTH_TOKEN)
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : ''
        }
      }
    })

    const client = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache()
    })

    ReactDOM.render(
      <BrowserRouter>
        <ApolloProvider client={client}>
          <App />
        </ApolloProvider>
      </BrowserRouter>, 
      document.getElementById('root')
    );

And this is where I try to extract it in Rails:

Rails.application.config.middleware.use Apartment::Elevators::Generic, lambda { |request|
  tenant_name = nil 


  if request.env["HTTP_AUTHORIZATION"]

    token = request.env["HTTP_AUTHORIZATION"]
    payload = JWT.decode token, Rails.application.secrets.secret_key_base, 'HS256'
    user_id = payload.first["user_id"]    
    tenant_name = User.find(user_id).subdomain
  end

  tenant_name
}

samedi 4 mai 2019

How to update Model attribute in Rails

SO I have this app, that let's users order shirt online.

This is how the item order looks, it has shirt size, shirt color, phone number, address, and order status.

enter image description here

I was modifying the existing code so that the admin users can change the order status from "ordered" into "processing", or "delivered" by selecting an option from a dropdown list beside the order status or to make it easier using a textfield by manually writing the supposed status, and click on submit button.

I get the view part, but I'm having difficulty with the update method in the controller, I don't know where to start being a novice rails coder myself.

SO this is my Model

class Micropost < ApplicationRecord
   belongs_to :user
   default_scope -> { order(created_at: :desc) }
   mount_uploader :picture, PictureUploader
   validates :user_id, presence: true
   validates :shirtSize, presence: true
   validates :shirtColor, presence: true
   validates :contactAddress, presence: true
   validates :contactNumber, presence: true
   validate  :picture_size
   #uncomment picture presence validation in the future
   # validates :picture, presence: true

   SIZE_LIST = [ " ", "S", "M", "L", "XL" ]
   COLOR_LIST = [ " ", "Black", "White", "Gray", "Red", "Green", "Blue", "Navy Blue", "Yellow", "Pink"]

   private

   # Validates the size of an uploaded picture.
   def picture_size
       if picture.size > 5.megabytes
          errors.add(:picture, "should be less than 5MB")
       end
   end
 end

VIEW

<li id="micropost-<%= micropost.id %>">
<%= link_to gravatar_for(micropost.user, size: 50), micropost.user %>
<span class="user"><%= link_to micropost.user.name, micropost.user %> 
</span>
<span class="content">
<%= "#{micropost.shirtSize}, #{micropost.shirtColor}" %>
<% if current_user?(micropost.user) || current_user.admin? %><br/>
  <%= "#{micropost.contactNumber} | #{micropost.contactAddress}" %> 
  <br/>
  <h4>Status: <%= micropost.orderStatus %></h4>
<% end %>
</span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
<% if current_user?(micropost.user) && micropost.orderStatus == "Ordered" %>
<%= link_to "Cancel", micropost, method: :delete,
                                 data: { confirm: "You sure?" } %>
<% end %>
</span>
<span class="content">
<%= image_tag micropost.picture.url if micropost.picture? %>
</span>
</li>

CONTROLLER

class MicropostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy, :update]
before_action :correct_user,   only: :destroy
before_action :admin_user,     only: :update

def create
  @micropost = current_user.microposts.build(micropost_params)
  if @micropost.save
    flash[:success] = "Design Posted!"
    redirect_to root_url
  else
    @feed_items = []
    render 'static_pages/home'
  end
end

def destroy
  @micropost.destroy
  flash[:success] = "Design deleted"
  redirect_to request.referrer || root_url
end

def update
  #Have no idea what to do here...
end

private

  def micropost_params
    defaults = { orderStatus: 'Ordered' }
    params.require(:micropost).permit(:shirtSize, :shirtColor, :contactNumber, :contactAddress, :picture).merge(defaults)
  end

  def correct_user
    @micropost = current_user.microposts.find_by(id: params[:id])
    redirect_to root_url if @micropost.nil?
  end

  # Confirms an admin user.
  def admin_user
    redirect_to(root_url) unless current_user.admin?
  end

end

jeudi 2 mai 2019

Sql - Correct Sum of field of base table with left outer join

I have this method which returns the final result for me to show, I have amount field in order table After this query I want that sum of amount field but at the same time I can't change get_raw_records because left outer join & filters is required

def get_raw_records
  Order.includes(:customers, :line_items).where(aasm_state: ['completed']).filers(.....)
end

get_raw_records.sum(:amount)

This sum is not correct as it has duplicate orders because of left outer join with line items

I am trying some other ways like but it distinct the amount not order records

get_raw_records.distinct.sum(:amount)

Any help to do this?, I can't change get_raw_records base query

How to replace a string with hash in ruby, using .gsubs?

I just started learning Ruby and I need to create a template where it replace my strings with hashes that I write. What I need to add in my code?

This is my code, I write two methods for my task, help please with your suggestions


  def initialize(template_string, local_variables)
   @template_string = template_string
   @local_variables = local_variables
end 

  def compile()
  @template_string.gsub()
end
end



puts Template.new("I like %{x}", x:"coffee").compile # x = coffee
puts Template.new("x = %{x}", y:5).compile # unknown x
puts Template.new("x = %{x}", x:5, y:3).compile # x = 5, ignores y

mercredi 1 mai 2019

After including rails engine layout in application gives routing error?

I am using Rails 5.2.3 and ruby 2.4.0p0

I already have an rails application, now I have created a new Rails engine with some functionality I have included it in the main application as:

In gemfile:

gem 'myengin', path: '/home/vidur/rails_apps/myengin'

For routing:

 mount Myengin::Engine => "/myengin", as: "myengin"   

I want to show the pages in the mounted engine inside the layout of the main application so for doing it I have extended the application controller of the main application in the application controller of the mounted engine as:

module Myengin
   class ApplicationController < ::ApplicationController
    protect_from_forgery with: :exception
  end
end

After doing it it will render the layout of the main application but it will give the routing errors, It will not detect the routing of the main application on these pages and show routing undefined error, But they exists in the routes.rb in the main application. Example:

undefined local variable or method `tukabank_cart_path' for #<#<Class:0x00000004e353b0>:0x00000004e237f0> 

defined in main application routed.rb as:

 resource :tukabank_cart, only: [:show]

similerly for other routes, all the variable defined as _path its gives undefined error But they are defined. why the routing is not getting detected on the of mounted engine pages, is there a way round, or should I keep the layout of the main application free from _path variable of the main application. thanks ain advance