vendredi 28 juin 2019

Net::SMTPAuthenticationError (535 5.7.3 Authentication unsuccessful [PN1PR01CA0089.INDPRD01.PROD.OUTLOOK.COM] )

I have tested the the account using my mail client and everything seems to be working fine, but when I try to send through my Rails 4 app I get the error:

config.action_mailer.smtp_settings = {
address: "smtp.live.com",
port: 587,
domain: Rails.application.secrets.domain_name,
authentication: "login",
enable_starttls_auto: true,

#tls: true,
user_name: Rails.application.secrets.email_provider_username,
password: Rails.application.secrets.email_provider_password,
openssl_verify_mode: 'none'}

mercredi 26 juin 2019

I want to concatinate two values into a single string

i have two different values systolic and diastolic blood pressure readings in string, i just want when those two values come from front-end i'll just store them into a single string E.g if systolic ='120' and diastolic='80' i want it to be bp='120/80'

module Api module V1 module CheckinMachine class BpsController < ApplicationController include MachineError before_action :authenticate_user!

    def create
      raise BatteryNotFunctionalError if battery_functional?
      # user = User.find_by!(bp_machine_imei: params[:imei])
      health_reading = current.health_readings.create!(key: :blood_pressure, value: bp_value)
      Solera::PostActivityApi.call(user,
                                   bp,
                                   health_reading.solera_activities.new)
      head :ok
    rescue ActiveRecord::RecordNotFound => _e
      render_machine_error and return
    end

    def show
      puts params
    end

    private

    def bp
      {
        systolic_blood_pressure: params[:systolic],
        diastolic_blood_pressure: params[:diastolic]
      }
    end
  end
end

end end

That's what i have tried, what do i do to make it exactly like i want it to be

like bp = '120/80'

lundi 24 juin 2019

how to build a tick box with rails on view/index

I am trying to build a tick box section with rails on view/index,these are all the steps I've taken so far i know that i need to do something about routes.rb, can you help?

this is the view:

<table class="table table-hover">
      <thead>
        <tr>
          <th>Coupon</th>
          <th>first_name</th>
          <th>surname</th>
          <th>email</th>
          <th>occupation</th>
          <th>validation</th>
        </tr>
      </thead>
    <tbody>
      <% @scooties_coupons.each do |scooties_coupon| %>
        <tr>
          <td><%= scooties_coupon.coupon %></td>
          <td><%= scooties_coupon.first_name %></td>
          <td><%= scooties_coupon.surname %></td>
          <td><%= scooties_coupon.email %></td>
          <td><%= scooties_coupon.occupation %></td>
          <td><%= link_to "Mark as Valid", method: :patch %></td>
        </tr>
      <% end %>
    </tbody>
    </table>


(i know to mark as valid should use link to but i am not too sure where to link to)

 create_table "scooties_coupons", force: :cascade do |t|
    t.string "coupon"
    t.boolean "redeemed", default: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "email"
    t.integer "expires_in"
    t.string "first_name"
    t.string "surname"
    t.string "oppcupation"
    t.string "occupation"
    t.boolean "validated"
    t.index ["coupon"], name: "index_scooties_coupons_on_coupon"
  end

(I've also created the validated as boolean in the db)

this is the controller:

def update

     @scooties_coupon = ScootiesCoupon.find(scooties_coupon_params)
     @scooties_coupon.update( scooties_coupon_params
    redirect_to scooties_coupons_new_path

  end


  def scooties_coupon_params
    params.require(:scooties_coupon).permit(:first_name, :surname, :email, :occupation)

  end

dimanche 23 juin 2019

How do I handle persistent currency switching throughout my app?

I support 3 currencies in my app GBP, JMD, USD.

When a user selects a currency on one page, it reloads the page and sets the session[:currency] variable accordingly. The challenge is, depending on the currency they select of the 3, the behavior isn't always predictable and the same.

I may have just been looking at this logic too long, but I can't figure out why it doesn't work and would love an extra pair of eyes.

So I started with this in my application_controller.rb:

unless params[:currency].blank?
  if params[:currency] != session[:currency] || session[:previous_currency].blank?
    session[:previous_currency] = session[:currency]
    session[:currency] = params[:currency] 
  end
else
  if session[:currency].blank?
    session[:currency] = 'JMD'
  end
end

That didn't really capture USD, GBP.

So that has since been modified to this:

unless params[:currency].blank? && session[:currency].blank?
  if (params[:currency].eql? "JMD") || (session[:currency].eql? "JMD")
    session[:currency] = 'JMD'
    session[:locale] = :en
    session[:previous_currency] = 'GBP'
  elsif (params[:currency].eql? "GBP") || (session[:currency].eql? "GBP")
    session[:locale] = :"en-GB"
  elsif (params[:currency].eql? "USD") || (session[:currency].eql? "USD")
    session[:locale] = :en
  elsif params[:currency] != session[:currency] || session[:previous_currency].blank?
    session[:previous_currency] = session[:currency]
    session[:currency] = params[:currency]
  end
else
  session[:currency] = 'JMD'
  session[:locale] = :en
end

The issue is this one doesn't work when I am going from any currency to GBP, and I can't quite figure out why.

What I mean is, say I change from USD to GBP. If I go to another page (say the homepage) it reverts to the default JMD currency. When I want it to stay GBP just like it does if I switch to USD and change pages everything stays in USD.

What am I missing?

lundi 17 juin 2019

possible to delete all rails session info for all users

I am working on a legacy Rails 3.2 app and would like to log everybody out and have their _app_session be reset with the secure flag set to true. It seems like either changing our session_store strategy to secure: true or config.force_ssl = true. Strangely only the latter seems to work correctly in Chrome.

The question is that it seems like the best way to log everyone one would be to remove their session variable and I tried this solution here https://stackoverflow.com/a/11422931/152825 of:

rake tmp:sessions:clear

but it didn't seem to work. Is there a better way to clear these session variables?

jeudi 13 juin 2019

get going to be executed query before execution on ActiveRecord::Base

I want to copy old_db.table data to new_db.table.

I used ActiveRecord::Base.connection.execute(sql) this method for executing my insertion query. That perfectly insert data to new_db.table . But I want to get the query before actual execution.

sql = "insert into `#{new_db}`.#{table} #{f} (select * from #{old_db}.#{table});"
ActiveRecord::Base.connection.execute(sql)

For example I want print "insert into new_db.table values(value1, value2, value3, ...)" something like this, the row-wise execution of my query. How can I do that?

how to add if statement in form with rails

I am trying to implement this logic into form based on the sku (where sku will determine the country and the country will determine the shipping option)

country = order&.shop&.country
    if (READY_FOR_SCHOOL_SKUS + STICKER_BOOK_SKUS).include?(product.sku)
      if country == "uk"
        shipping_option = ShippingOption.find_by(name: "RoyalMail48")
      else
        shipping_option = ShippingOption.find_by(name: "TPLP")
      end
      return shipping_option
    end
    if (DICTIONARY_SKUS + WORD_OF_DAY_SKUS).include?(product.sku)
      if country == "uk"
        shipping_option = ShippingOption.find_by(name: "RoyalMail48")
      else
        shipping_option = ShippingOption.find_by(name: "standard_3_to_10_days")
      end
      return shipping_option
    end
    if (RFS_STICKER_BOOK_SKUS + USA_SUBSCRIPTION_SKUS + UK_SUBSCRIPTION_SKUS).include?(product.sku)
      if country == "uk"
        shipping_option = ShippingOption.find_by(name: "dhl")
      else
        shipping_option = ShippingOption.find_by(name: "TPLP")
      end
      return shipping_option
    end

<% @product.product_shop_shipping_options.uniq(&:shop).each_with_index do |psso, i|%>
  <%= f.fields_for :product_shop_shipping_options, psso do |s| %>
    <%= s.label psso.shop.shopify_shop_name %>
    <%= s.hidden_field :shop_id %>
    <%= s.grouped_collection_select :shipping_option_id, @fulfilment_centres, :shipping_options, :name, :id, :name, {prompt: 'Select shipping option'}, { class: 'form-control'} %>
  <% end %>
<% end %>

mercredi 12 juin 2019

In Ruby 1.8.7, why does JSON syntax in IRB raise a Syntax, but not in a Rails 3.2.22.1 console?

I'm responsible for maintaining a legacy Ruby on Rails application, and I'm currently testing it on Ruby v1.8.7 (2013-12-22 patchlevel 375). The app is using Rails v3.2.22.1 (a Rails version provided by Rails LTS). I am bumping into a weird syntax issue.

In a vanilla IRB console, the hash rocket syntax for a Hash works as expected, and the JSON syntax for raises a syntax error as expected. However, in a Rails console, the JSON syntax is working just fine, and I can't figure out why it's NOT raising a syntax error.

Any ideas what is going on in the code below?

# in Bash
$ ruby -v
ruby 1.8.7 (2013-12-22 patchlevel 375) [i686-darwin18.2.0]

# in Rails console
Loading development environment (Rails 3.2.22.1)
irb(main):001:0> system "ruby -v"
ruby 1.8.7 (2013-12-22 patchlevel 375) [i686-darwin18.2.0]
=> true
irb(main):002:0> {a: 1} # JSON syntax doesn't trigger SyntaxError
=> {:a=>1} 
# loading vanilla IRB *()
irb(main):003:0> system "irb" # loading vanilla IRB

# in vanilla IRB (via Rails console, if that matters)
irb(main):001:0> system "ruby -v"
ruby 1.8.7 (2013-12-22 patchlevel 375) [i686-darwin18.2.0]
=> true
irb(main):002:0> {a: 1} # expected syntax error
SyntaxError: compile error
(irb):2: odd number list for Hash
{a: 1}
   ^
(irb):2: syntax error, unexpected ':', expecting '}'
{a: 1}
   ^
  from (irb):2

mardi 11 juin 2019

get the id from url and use it to get a specific data from a table

I am doing a project for my studies. How can I get the id from the URL and pass it to the controller to get specific data from the table

This some of codes I have tried

class MajorsController < ApplicationController
  before_action :set_major, only: [:show, :edit, :update, :destroy]

  # GET /majors
  # GET /majors.json
  def index
    @majors = Major.all
  end

  # GET /majors/1
  # GET /majors/1.json
  def show
    @majors = Major.all
    @courses = Course.where(params[:major_id])
  end

i expect the output is the only two courses i have but it output them all

Can you create a ruby api application on top of existing schema?

I am fairly new to Ruby on Rails. I am using it to create a web API application and was wondering if instead of creating a schema based on my Model, can I do the reverse? E.g. is it possible to create model that would fit with an already existing schema? Something like that would be fairly easy in Java World using JPA but I am not so sure about Rails using DSL for databases.

Do I have to manually change the migration files in this case? If yes, is there an easy/recommended way to do this?

Thanks

Best way to combine results of two select statements without returning an array?

I'm trying to get one set of unique users from querying two different tables. For example, let's say I want to find the set of unique pet owners. Some owners own dogs, some own cats- I want the number of owners who own a dog or a cat or both.

I know one solution is

dog_owners = Dog.joins(:owner).select(:owner_id).distinct
cat_owners = Cat.joins(:owner).select(:owner_id).distinct
combined_owners = dog_owners + cat_owners
unique_owners = combined_owners.uniq{|x| x.owner_id}
unique_owners.count 

Is there a way to do this where I wouldn't have to use the uniq call, and could use distinct instead? Because the + operator returns an Array, I am not able to use distinct here.

lundi 10 juin 2019

How to prevent the carriage return character that appends in a html form textarea?

I just encountered a bug in my rails3 application while setting up WhatsApp messaging service via a third party API.

I have my message template set at the 3rd party portal. Now when my client is hitting the API with the message content, I encounter the response : "error | 318 | Message does not match WhatsApp HSM template."

After thorough debugging I realised the message content (which is an input from admin on my application) appends a "\r" character before every "\n" character when the content is submitted via html form.

However the content at the 3rd party has only "\n" character leading to the mismatch.

I need help with how I can avoid "\r" append.

I read the cause could be a copy paste from different encoding sources, like MS Word. I tried to test this theory with (Ubuntu) LibreOffice Writer and Text Editor, and it was of no use.

However if I update the content with rails console, I get the desired result (no "\r" append)

This is how my data looks in 2 scenarios:

Through input in an html form: (actual) Some text \r\n\r\nFor more details, check out this.

Through rails console: (desired) Some text \n\nFor more details, check out this.

How do I update controller param to accept nested attributes with rails?

I am working on a rails app, I was wondering how to update controller params to accept nested attributes with rails, this is the existing controller;

def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to product_path(@product), notice: 'Product was successfully created.'
    else
      render :new
    end
  end

  def update
    if product.update(product_params)
      redirect_to product_path(product), notice: 'Product was successfully updated.'
    else
      render :edit
    end
  end

 def product_params
    params.require(:product).permit(
      :sku, :name, :shipping_option_id, :product_region_id
    )
  end

I was wondering if I need to add a different attribute, do I do it with create or update method in controller?

vendredi 7 juin 2019

How to add a new field to a form Rails?

I am trying to add a new filed to a form with Rails for each field needs to have a dropdown of shipping options with the value of: shipping_option_id:

How do I do it with form?

Schema

 create_table "products", force: :cascade do |t|
    t.string "sku"
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "shipping_option_id"
    t.bigint "product_region_id"
    t.index ["product_region_id"], name: "index_products_on_product_region_id"
    t.index ["shipping_option_id"], name: "index_products_on_shipping_option_id"
    t.index ["sku"], name: "index_products_on_sku", unique: true
  end

how to transform a text file into a 3D representation in C#

i have a test file of 5 columns and many lines which contains the values of type Float and i would like to turn this test file into 3 D representation. I really do not know how to do it.

thank you for Help

jeudi 6 juin 2019

ActiveRecord query to retrieve frequency depending on a condition

Please, read everything

Hello, I need to make some more or less complex calculations (at least for me), I've made a query with several joins to combine several tables and select some columns, but now I have to calculate the frequency of a field, this field is deliver.status_id, the problem is I have to do this calculation taking into account only one deliver_group.id, what do I mean by this? let's make an example:

If I have these selected columns...

|---------------------|------------------|
|  deliver.status_id  | deliver_group.id |
|---------------------|------------------|
|          1          |         10       |
|---------------------|------------------|
|          3          |         11       |
|---------------------|------------------|
|          4          |         12       |
|---------------------|------------------|
|          2          |         12       |
|---------------------|------------------|
|          1          |         12       |
|---------------------|------------------|
|          2          |         13       |
|---------------------|------------------|
|          3          |         13       |
|---------------------|------------------|

Then the deliver.status_id frequency would be {1 => 2, 2 => 2, 3 => 2 4 => 1}, but as I said I only have to take into account the one occurrence of deliver_group.id, this means the frequency would be {1 => 1, 2 => 1, 3 => 1, 4 => 1}, cause I have to "ignore" deliver.status_id when the deliver_group.id is repeated.

|---------------------|------------------|
|  deliver.status_id  | deliver_group.id |
|---------------------|------------------|
|          1          |         10       |
|---------------------|------------------|
|          3          |         11       |
|---------------------|------------------|
|          4          |         12       |
|---------------------|------------------|
|          2          |   12 (ignored)   |
|---------------------|------------------|
|          1          |   12 (ignored)   |
|---------------------|------------------|
|          2          |         13       |
|---------------------|------------------|
|          3          |   13 (ignored)   |
|---------------------|------------------|

Another example:

|---------------------|------------------|
|  deliver.status_id  | deliver_group.id |
|---------------------|------------------|
|          1          |         7        |
|---------------------|------------------|
|          3          |         8        |
|---------------------|------------------|
|          4          |         9        |
|---------------------|------------------|
|          2          |    9 (ignored)   |
|---------------------|------------------|
|          1          |         10       |
|---------------------|------------------|
|          2          |         11       |
|---------------------|------------------|
|          3          |   11 (ignored)   |
|---------------------|------------------|
|          3          |   11 (ignored)   |
|---------------------|------------------|
|          3          |         12       |
|---------------------|------------------|
|          3          |   12 (ignored)   |
|---------------------|------------------|
|          3          |   12 (ignored)   |
|---------------------|------------------|

Would result in {1 => 2, 2 => 1, 3 => 2, 4 => 1}.

By the way, I don't want to do this with ruby syntax, I mean, I know how to do this with a Hash and an iterator, blah, blah, blah, but I want to make the calculations completely with a query because the performance is key in this app

I know the case where nothing is ignored is quite simple, query.group('deliver.status_id').count, but I'm lost with my actual case.

How can I divide sum for a of two column for a certain condition in rails

I want to create a result system. How can I calculate this cgpa for a semster.

I'm trying to show the cgpa only those of which semester is searched along with subject detail.

Calculation for that cgpa is: Sum(credit*gpa)/Sum(credit).

I have saved credit*gpa in a column for subject table.

I can find normal cgpa using

cgpa = <%= Subject.sum(:cXgpa)/ Subject.sum(:credit) %> But I need to find it for semester searched

table is

t.string "subject_name"
t.string "subject_code"
t.float "credit"
t.float "gpa"
t.float "cXgpa"
t.integer "semester_id"

I tried this to find it

<small class="text-warning">cgpa = <%=  Subject.pluck('sum(subjects.cXgpa) /    sum(credit)').where(:semester_id=>params[:semester]) %></small>

mercredi 5 juin 2019

Problem with Value That change for some reason

Just run this code in console. Problem is @notes_before change value after calling method "a.move" for some reasons. How to fix it and why it happen ?

class Slider
  attr_accessor :position
  def initialize(position)
    @position = position
    @notes_before = Array.new
  end

  def move
    @position.each do |note|
      note[0] +=1
    end
    print @notes_before
  end

  def update_pos
    @position.each do |notes|
      @notes_before << notes
    end
    print @notes_before
  end
end

a=Slider.new([[0,0],[0,1]])
a.update_pos
a.move

I expect output of @notes_before to be [[0, 0], [0, 1]] after calling a.move but the actual output is [[1, 0], [1, 1]]

How to click a (apparently) form-less button/ link using mechanize to 'Show More' on web page

I would like to load more data onto the page I'm visiting by clicking the 'Show More' button, which is at the bottom of the page.

Mechanize is showing me this button as a link (see below).

From the research I've done, I should be able to click this button with the code listed below. However, when I view the list of divs that I'm hoping will be longer, I see the count is the same as before, which to me means something isn't working as expected.

On another thread, I saw that buttons can sometimes be 'disguised' as part of forms. I looked at the page and it has three forms. However I do not believe any of these forms are associated with this button because the button does not have any fields associated with it.

When I do invoke the click method below, it does look like the click was successful (I can see some sort of reload in terminal) but .children.count does not change.

#assume I already did mechanize.get(url) and I'm on the site.
#I also did a mechanize.page.links.find to get the show more button

mechanize = Mechanize.new 
showMore = #<Mechanize::Page::Link "Show More" "#">
pageWithMore = mechanize.click(showMore)

# check children of div to see if count is longer
mechanize.page.css('div.results-container').children.count
# repeatedly returns 51 after 'click' invoke 

I expect the .children.count to be closer to 100 after invoking the click method and then ~150 after invoking a second time.

rails syntax error when add column to model

I am trying to build a music app with rails where I encountered error, just wondering does anyone know what it means?

when I did rails g migration add_quantity_to_line_items quantity:integer, default: 1

rails db:migrate

which threw back rails aborted! SyntaxError: /Users/Code/Ruby/musicapp/db/migrate/20190605091214_add_quantity_to_line_items.rb:4: syntax error, unexpected tSYMBEG, expecting do or '{' or '(' add_column :line_items, :default, :string ^ /Users/mrswordsmith/Code/Ruby/musicapp/db/migrate/20190605091214_add_quantity_to_line_items.rb:5: syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END add_column :line_items, :1, :string

class AddQuantityToLineItems < ActiveRecord::Migration[5.2]
  def change
    add_column :line_items, :quantity, :integer,
    add_column :line_items, :default, :string
    add_column :line_items, :1, :string
  end
end

mardi 4 juin 2019

When is it a good idea to define a static ruby class?

Are there some governing rules around when it makes sense to define a static class as opposed to a class that is instantiated?

Still puzzling over idiomatic ruby initialization vs static class definition.

From what I've found.

Static classes seem very effective.

  1. ruby is both a functional and object orientated language. it’s very possible to write both styles. a functional style in super useful for ‘functional’ things. some pieces of our our code base are static, others are instantiated.
  2. i regularly observe classes going from static to instantiated and then very quickly bloating. “now we have all this stuff.. why not do more.“. static classes have a natural tendency to taking on multiple responsibilities.
  3. when a class transitions from static to instantiated we arrive at less unit testing confidence, given things at run time might change in regards to memory allocation / assignment (as in, someone could accidentally get in between instantiation and call).
  4. static classes are easier to read because we don’t have to juggle potential state change considerations. less mutation = less complexity.

For me. The big issues are:

  1. Classes doing more than one thing.
  2. Instability in patterns across large old ruby code bases.

To address these 2 concerns, I’m thinking a static approach (where possible) seems to put a healthy amount of pressure on the code to adhere to SOLID principles.

Static

Serializer.transform(fruit:)

Instantiated

Serializer.new(fruit:).transform

What drives you to go static in ruby?

lundi 3 juin 2019

How to segregate rake from executing production DB commands from development environment?

I just noticed that a rake drop all command can also drop tables in the production db instance. Is there a way in rails to separate rails config so that the production systems are not touched by any commands from development environments ?

Rails unknown attribute during data seeding

I have an error message - "ActiveModel::UnknownAttributeError: unknown attribute 'price' for Product." I've also run rails generate migration add_Price_to_Productbut still threw me this error while seeding. I've also run this rails g model Product name 'price:decimal{12,3}' active:booleanand threw back a migration conflict from the previous migration! I am trying to create a rails shopping cart; any help would be very much appreciated.

Thank you!

this is the schema.rb

  create_table "products", force: :cascade do |t|
    t.string "product_name"
    t.string "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "condition"
    t.string "name"
    t.integer "user_id"
  end

this is product.rb

class Product < ActiveRecord::Base
  has_many :order_items

  default_scope { where(active: true) }
end


Rails Active Admin menu :label is not working anymore

After updating from activeadmin 1.0.0.pre5 to 1.0.0 the menu items labels are not shown correctly.

The code below is what we have been always had and worked perfectly. We're expecting to see a menu item in the Active Admin called "MODIFICACIONS EN DIRECTE". However, now it just takes it from the ":as" parameter thus the label shown es "Arribadas" (because it also pluralize it) and ignores completely the "menu :label => "MODIFICACION..."

ActiveAdmin.register ResultatProvisional, :as => 'arribada' do
  belongs_to :cursa, :finder => :find_by_slug, parent_class: Cursa
  before_action :left_sidebar!
  menu :label => "MODIFICACIONS EN DIRECTE", :priority => 1

  navigation_menu :cursa
  config.clear_action_items!

Thanks in advance for your help,

Yeray