jeudi 31 décembre 2020

Using Ruby to get email attachment ID

I am trying to loop through a set of emails, and get their email attachment ID. I can't seem to get down to the ID, though.

I've gotten this far:

class AccessEmailController < ApplicationController

def access_email

    client = Signet::OAuth2::Client.new(access_token: session[:access_token])
    service = Google::Apis::GmailV1::GmailService.new
    service.authorization = client

    user_id = 'me'

    email_list = service.list_user_messages('me', q: "subject:(CCC Data)")
    
    message = 'No Emails Found' if email_list.messages.empty?
   
    email_list.messages.each do |message|
        message_id = message.id
        @subject = service.get_user_message(user_id, message_id).payload.parts

    end
end

end

And, if I display @subject in a view, I get:

[#<Google::Apis::GmailV1::MessagePart:0x00007f8630c397a0 @headers=[#<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c344a8 @name="Content-Type", @value="multipart/alternative; boundary=\"00000000000020396d05b7ceda38\"">], @mime_type="multipart/alternative", @body=#<Google::Apis::GmailV1::MessagePartBody:0x00007f8630c39250 @size=0>, @filename="", @part_id="0", @parts=[#<Google::Apis::GmailV1::MessagePart:0x00007f8630c30588 @headers=[#<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c2d2e8 @name="Content-Type", @value="text/plain; charset=\"UTF-8\"">], @mime_type="text/plain", @body=#<Google::Apis::GmailV1::MessagePartBody:0x00007f8630c2ed50 @size=91, @data="-- \r\nKim Floyd (Davis)\r\n\r\nWeb Developer, EvenVision\r\n707.845.3073\r\nk.davis@evenvision.com\r\n">, @filename="", @part_id="0.0">, #<Google::Apis::GmailV1::MessagePart:0x00007f8630c2be98 @headers=[#<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c2a840 @name="Content-Type", @value="text/html; charset=\"UTF-8\"">, #<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c29ff8 @name="Content-Transfer-Encoding", @value="quoted-printable">], @mime_type="text/html", @body=#<Google::Apis::GmailV1::MessagePartBody:0x00007f8630c2b858 @size=344, @data="<div dir=\"ltr\"><br clear=\"all\"><div><br></div>-- <br><div dir=\"ltr\" class=\"gmail_signature\" data-smartmail=\"gmail_signature\"><div dir=\"ltr\">Kim Floyd (Davis)<div><br><div>Web Developer, EvenVision</div><div>707.845.3073</div><div><a href=\"mailto:k.davis@evenvision.com\" target=\"_blank\">k.davis@evenvision.com</a></div></div></div></div></div>\r\n">, @filename="", @part_id="0.1">]>, #<Google::Apis::GmailV1::MessagePart:0x00007f8630c28f68 @headers=[#<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c27b90 @name="Content-Type", @value="image/png; name=\"image.png\"">, #<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c26fd8 @name="Content-Disposition", @value="attachment; filename=\"image.png\"">, #<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c266f0 @name="Content-Transfer-Encoding", @value="base64">, #<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c25d40 @name="X-Attachment-Id", @value="f_kjdr80n00">, #<Google::Apis::GmailV1::MessagePartHeader:0x00007f8630c25250 @name="Content-ID", @value="<f_kjdr80n00>">], @mime_type="image/png", @body=#<Google::Apis::GmailV1::MessagePartBody:0x00007f8630c28a90 @size=459005, @attachment_id="ANGjdJ9LKnYW-GChtR3_oaBWnwi0DjHG4I8ZeDuMskuJ6htxLGmwNaB-v3x0k_cP94ybJFg0HLPO0AkSLWb-zXvF25qaGyhA20R89kwPSC9j3ttVEsBhByEAxrPkJQVwKuf3H8EblPhNNfPA7iYEJ7zT56do8-_UbMbDuXo-fVU445mtPHSYHWOEX_4z8aUyNTU3MCzNY8EHz90mJRpJnseelK3whaZdcJ2E98XmxQ">, @filename="image.png", @part_id="1">]

Which, does contain the attachment I am looking for. How can I get down to that attachment, though, and get it's ID?

mercredi 30 décembre 2020

run ruby file from ajax or on button click event

i am new in ruby. so i have html code which includes one input field and button and i want when user click on that button i have to run one ruby file which has system() method.

index.html


     <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
     </head>
     <body>
        <form method="post" action="/runMethod">
           <input type="text" name="name" value="whatever">
           <input class='btn btn-primary' type='submit' value='click'>
        </form>
     </body>

   

app.rb

 system("wayback_machine_downloader userInput")

this is my two files code. i just want that if i click on button app.rb file should run with given input. is it possible?

mardi 29 décembre 2020

dimanche 27 décembre 2020

Does anyone know why IRB gives the syntax error in block?

It's just plain ruby. Any ideas why the code below throws syntax error?

irb(main):001:0> def count_valid_policies(input)
irb(main):002:1>   counter = 0
irb(main):003:1>   policies = input.split("\n")
irb(main):004:1>   policies.each do |policy|
irb(main):005:2*     valid?(policy) && counter++
irb(main):006:2*   end
irb(main):007:1>
irb(main):008:1>   puts counter
irb(main):009:1> end
Traceback (most recent call last):
        1: from /usr/local/bin/irb:11:in `<main>'
SyntaxError ((irb):6: syntax error, unexpected keyword_end)
  end
  ^~~
(irb):9: syntax error, unexpected end-of-input, expecting keyword_end

lundi 21 décembre 2020

How can I make a Rails which can auto locate place and display as google map?

I am trying to make a simple program which can locate your place, for example when you enter your place my program will display your map as google map.

When I search by google, they said that I can use Gmaps4rails, but unfortunately that it seems obsolete and I can not use it anymore.

Could you please give me any idea? Or some link ?

Thank you very much.

Fetch an image file kept at server using JS in rails

I am using rails v 3.2 and ruby v - 1.9. I have been trying to work this out and after a lot of googling can't find a solution. If there are certain files created at runtime at the server side, how do i fetch them and show them to the user i'e; the client side using JS. please note that there can be any number of files and are mainly images and all of them need to be shown at once. any help would be great.

vendredi 18 décembre 2020

ruby on rails ails with couldn't find file jquery.ui.all

couldn't find file 'jquery.ui.all' which is a known issue, I added *=require jquery.ui.all to application.css and //= require jquery.ui.all to application.js but still get the error.

I already installed "jquery-ui-rails" and "jquery-rails"

mercredi 16 décembre 2020

Why I can not delete object when click destroy in Rails?

I am trying to click link destroy but it going to in the page details? I use CRUD default of rails Here is the code :

tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.tittle %></td>
        <td><%= post.body %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>

Why I can not delete object when click destroy in ruby on rails [closed]

Please me ask why when I click link destroy but it going to in the page details? I use CRUD defaut of rails Here is the code:

<p id="notice"><%= notice %></p>

<h1>Posts</h1>

<table>
  <thead>
    <tr>
      <th>Tittle</th>
      <th>Body</th>
      <th colspan="3"></th>
   </tr>
 </thead>

  <tbody>
    <% @posts.each do |post| %>
      <tr>
        <td><%= post.tittle %></td>
        <td><%= post.body %></td>
        <td><%= link_to 'Show', post %></td>
        <td><%= link_to 'Edit', edit_post_path(post) %></td>
        <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
        </td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New Post', new_post_path %>

Thank you everyone

lundi 14 décembre 2020

Ruby efficient each loop

Is there a better way to write this? markdown is a StringIO

coverage_hash_arr.each do |the_hash|
    markdown << "------- Status on #{the_hash[:Module]} -------\n"
    the_hash.delete(:Module)
    the_hash.each {|key, value| markdown << "- #{key}: #{value} \n"} 
    markdown << "----------------------------------------------\n"
end

samedi 12 décembre 2020

JWT Auth giving error when attempting to login user

Im using JWT with a Rails backend/React frontend. Im attempting to have my user redirected when they log into their account to the /home page of the site. The error I am receiving is

TypeError: Cannot read property 'push' of undefined
Login.<anonymous>
src/components/Login.js:20
 17 |   if(res.user){
 18 |     localStorage.token = res.token
 19 |     this.setState({user:{id:res.user.id, username:res.user.username, token:res.token}, home:res.user.home}, () => {
> 20 |     this.props.history.push('/home')
    | ^  21 |   })
 22 | } else {
 23 |     alert(res.error)

Ive did make a change, to the home component but since reverted back to what it was but still having issues....

my controllers...

class ApplicationController < ActionController::API
  def encode_token(payload)
      JWT.encode(payload, "coffee")
  end 

def auth_header
  # { Authorization: 'Bearer <token>' }
  request.headers['Authorization']
end

def decoded_token
  if auth_header
    token = auth_header.split(' ')[1]
    # header: { 'Authorization': 'Bearer <token>' }
    begin
      JWT.decode(token,'coffee', true, algorithm: 'HS256')
    rescue JWT::DecodeError
      nil
    end
  end
end

def current_user
  if decoded_token
    user_id = decoded_token[0]['user_id']
    @user = User.find_by(id: user_id)
  end
end

def logged_in?
  !!current_user
end

def authorized
  render json: { message: 'Please log in' }, status: :unauthorized unless logged_in?
end
end
----
class UsersController < ApplicationController
    before_action :authorized, only:[:persist]

    def create
        @user = User.create(user_params)
        if @user.valid?
            token = encode_token({user_id: @user.id})   
            render json: @user
        else 
            render json: {error:'failed to create a user'}
        end
    end 

    def login
        @user = User.find_by(username:params[:username])
        if @user && @user.authenticate(params[:password])
            token = encode_token({user_id: @user.id})
            render json: {user:UserSerializer.new(@user), token:token}
        else
            render json: {error:"wrong user or password"}
        end 
        
    end 
    
    def index 
        @user = User.all
        render json: @user
    end
    def persist
        token = encode_token({user_id: @user.id})
        render json: {user:UserSerializer.new(@user), token:token} 
    end 

    private 
    def user_params
        params.permit(:username, :password)
    end 
end

my user_serializer...

class UserSerializer < ActiveModel::Serializer
    attributes :id, :username
    has_many :favorites
    has_many :favorite_coffee_shops, through: :favorites, source: :coffee_shop
    has_many :reviews
    has_many :coffee_shops, through: :reviews
  end

my login component...

import React from 'react';
import SignUp from './SignUp';

class Login extends React.Component{

    state={
      user:{
        id:0,
        username:"",
        token:""
      },
      home:[]
    }
     

       handleAuthResponse = (res) => {
         if(res.user){
           localStorage.token = res.token
           this.setState({user:{id:res.user.id, username:res.user.username, token:res.token}, home:res.user.home}, () => {
           this.props.history.push('/home')
         })
       } else {
           alert(res.error)
         }
       }

       handleLogin = (e, userInfo) =>{
        e.preventDefault()
        console.log(e)
     
        fetch('http://localhost:3000/login',{
         method:"POST",
         headers:{
           'Content-Type':'application/json'
         },
         body:JSON.stringify(userInfo)
       })
       .then(res => res.json())
       .then(json => {
         console.log(json)
         if(!json.error){
           this.handleAuthResponse(json)
         }else {
           alert(json.error)
         }
       })
       .catch(err => console.log(err))
      }
     
      
handleChange = (e) => {
  let {name, value} = e.target
  this.setState({
    [name]: value
  })
}


render(){
  return (
    <div className="login">Welcome Back!
     <form onSubmit={(e) => this.handleLogin(e, this.state)}>
       <div>
         <label>UserName</label>
         <br></br>
         <input type="text" name="username" value={this.state.username} onChange={this.handleChange}/>
         </div>
         <div>
         <label>Password</label>
         <br></br>
         <input type="password" name="password" value={this.state.password} onChange={this.handleChange}/>
         </div>
         <input type="submit" value="Submit" className="sl-btn" />
      </form>
      <div></div>
      <SignUp />
    </div>
  );
}
}

export default Login;

and my home component im attempting to push the user to once logged-in

import React from 'react'
import MapContainer  from '../containers/MapContainer'
import NavBar from './NavBar'
import FavoritesContainer  from './FavoritesContainer'

class Home extends React.Component {

    state = {
        reviews: [],
        favorites: [],
    }

    componentDidMount(){
    fetch('http://localhost:3000/reviews')
    .then(res => res.json())
    .then(reviews => this.setState({ reviews }))
    }
              
    addReview = (review) => {
        fetch('http://localhost:3000/reviews',{
            method: "POST",
            headers: {
                "Content-Type" : "application/json",
                Accept: "application/json",
                Authorization: `bearer ${localStorage.token}`
            },
            body: JSON.stringify({ review: review }
            ),
        })
        .then(res => res.json())
        .then(( json => {
            this.setState(prevState => ({
                reviews: [...prevState.reviews, json ]
               }))
        }))
    }
  
    render() {
        return (
               <div className="home">
                   <NavBar />
                   <MapContainer />
                   <FavoritesContainer />
           </div>
        )
}
}

export default Home

I am pretty new dev, please let me know if there is anymore info needed to help diagnose the problem. any advice would be helpful, thank you!!

jeudi 10 décembre 2020

Uploading .heic images in Rails 3.2 using paperclip gem

Users are unable to upload .heic images. Doesn't seem to be as simple as adding "images/heic" to content_type validations or just changing the file type to .jpg or .png. Is there a way to get this done using paperclip or should we use an API to convert the .heic image to .jpg or .png before attaching and uploading?

mercredi 9 décembre 2020

Questions and Simple Problems using ruby on rails?

I'm going to attend the final round of interview. They said they will ask the simple problems on ruby on rails from the below topics and bit deep fundamentals on these topics.

Senior Programmers in ruby on rails kindly suggest me some problems and question from these topics that you will ask to the candidate when you interview them?. It helps me a lot during this pandemic to get job.

SECTION: THE RUBY PROGRAMMING LANGUAGE.

  • TOPICS: ▪ Working with strings. ▪ Working with numbers. ▪ Methods. ▪ Branching if/elsif/else/end. ▪ Operators. ▪ Array and Iterators. ▪ Hashes. ▪ Object Oriented Programming. ▪ Attributes, getters, setters. ▪ ‘Self’ notation for method names.

• SECTION: INTRODUCTION TO RUBY ON RAILS.

  • TOPICS: ▪ Model, View and Controller. ▪ Rail App Structure. ▪ Root route, controller, more MVC. ▪ Structure of Rails Application. ▪ Front-End: Learn basic HTML, CSS. ▪ Add about Page. ▪ The back-end: Database and tables. ▪ The back-end: CRUD scaffold.

• SECTION: CRUD OPERATION IN RUBY ON RAILS.

  • TOPICS: ▪ Tables. Migration and naming convention. ▪ Models and rails console. ▪ CRUD operation from rails console. ▪ Validations. ▪ Route, action, view. ▪ Index, new article form.
    ▪ Create action. ▪ Edit and update existing. ▪ Delete. ▪ User Interface. ▪ DRY code.

mardi 8 décembre 2020

Trying to get reviews for a specfic game

Im attempting to see reviews for a specific game that ive created. Right now my reviews/index show for all games, not just the specific game im looking for. Im assuming its just something im missing in my params but not sure...

these my are controllers...

class ReviewsController < ApplicationController
  before_action :set_review, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except:[:index, :show]
  before_action :correct_user, only: [:edit, :update, :destroy]

  def index
    @reviews = Review.all
  end

  def show
    @review = Review.find(params[:id])
  end 
...
class GamesController < ApplicationController
  before_action :set_game, only: [:show, :edit, :update, :destroy]
 
  def index
    @games = Game.all
  end


  def show
  end

my routes ...

reviews#index
                                      POST   /games/:game_id/reviews(.:format)                                                        reviews#create
                      new_game_review GET    /games/:game_id/reviews/new(.:format)                                                    reviews#new
                     edit_game_review GET    /games/:game_id/reviews/:id/edit(.:format)                                               reviews#edit
                          game_review GET    /games/:game_id/reviews/:id(.:format)                                                    reviews#show
                                      PATCH  /games/:game_id/reviews/:id(.:format)                                                    reviews#update
                                      PUT    /games/:game_id/reviews/:id(.:format)                                                    reviews#update
                                      DELETE /games/:game_id/reviews/:id(.:format)                                                    reviews#destroy
                                games GET    /games(.:format)                                                                         games#index
                                      POST   /games(.:format)                                                                         games#create
                             new_game GET    /games/new(.:format)                                                                     games#new
                            edit_game GET    /games/:id/edit(.:format)                                                                games#edit
                                 game GET    /games/:id(.:format)                                                                     games#show
                                      PATCH  /games/:id(.:format)                                                                     games#update
                                      PUT    /games/:id(.:format)                                                                     games#update
                                      DELETE /games/:id(.:format)                                                                     games#destroy
                                 root GET    /                                                                                        games#index

this is how im attempting to do my link_to but its showing all the games reviews in my seeds not just a single game and all its reviews...

<%= link_to 'reviews', game_reviews_path(game_id: @game.id), @reviews %>

first RoR prj on my own, any help would be great!!

thanks!

lundi 7 décembre 2020

Unable to get my edit button to work with form_with helper

I'm attempting to create an Edit action with form_with in Rails.... My other CRUD actions are working ok, so something to do with my form_with...

<%= form_with(model: [@game, @review], local:true) do |form| %>

this is the tag im attempting to create, yet when I do i get this error

undefined method `review_path' for #<#<Class:0x00007fedfa8befd0>:0x00007fedfa8bd298>
Did you mean?  view_paths

directing me back to the tag, this is my controller

def new
   @game = Game.find(params[:game_id])
   @review = current_user.reviews.new
  end

  # GET /reviews/1/edit
  def edit
  end

  # POST /reviews
  # POST /reviews.json
  def create
    @review = current_user.reviews.new(review_params)
    @game = Game.find(params[:game_id])
    @review.game_id = @game.id

    respond_to do |format|
      if @review.save
        format.html { redirect_to game_reviews_path(@review), notice: 'Review was successfully created.' }
        format.json { render :show, status: :created, location: @review }
      else
        format.html { render :new }
        format.json { render json: @review.errors, status: :unprocessable_entity }
      end
    end
  end
  # <%= link_to "New Review", new_game_review_path(game_id: @game.id) %>


  # PATCH/PUT /reviews/1
  # PATCH/PUT /reviews/1.json
  def update
    @review = current_user.reviews.update(review_params)
    @game = Game.find(params[:game_id])
    @review.game_id = @game.id

    respond_to do |format|
      if @review.update(review_params)
        format.html { redirect_to @review, notice: 'Review was successfully updated.' }
        format.json { render :show, status: :ok, location: @review }
      else
        format.html { render :edit }
        format.json { render json: @review.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /reviews/1
  # DELETE /reviews/1.json
  def destroy
    @review.destroy
    respond_to do |format|
      format.html { redirect_to game_reviews_path(@review), notice: 'Review was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def correct_user
    @review = current_user.reviews.find_by(id: params[:id])
    redirect_to reviews_path, notice:" Not Authorized to Edit This Review" if @review.nil?
    end

Still pretty new to Rails, any help would be great!

Thanks

Trix editor rails

I am creating an article and on the index page I want to show the table in which I'll give the list of the particular article's attachments. How can I get the list of attachments for a particular article I have created. I have searched many things and unable to find any solution.

Action-text-editor-validation in rails

If in a blog I have 2 action text editors. Say one for comments and one for articles. If I wanted to handle the attachments for only of comments editor i.e. I want to pass only image in comments attachments and the article trix editor should be same. How to implement this. I used this but it is getting implemented with both editors.

comment_form

<%= form_with model: @comment do |f| %>
            <div class="class="card mb-2"">
              <div class="card-body">
            <h4><%= f.label :Comment %></h4>
              <%= f.rich_text_area :body %>
            </div>
            </div>
              <%= f.submit 'Comment', :class => 'pull-right btn-info btn-lg'%>
          <% end %>


<script type="text/javascript">
  window.addEventListener("trix-file-accept", function(event) {
  event.preventDefault()
  alert("File attachment not supported!")
})
</script>

jeudi 3 décembre 2020

SQLite3::SQLException: near "at": syntax error

I keep getting this error when trying to loop through the jobs i have , here is the code :

- @jobs.each do |job|
  %h2= job.title
  %p= job.company 

this exception the :"SQLite3::SQLException: near "at": syntax error" its not identifying the "-" at the beginning of the line. My file is a .html.haml file.

mercredi 2 décembre 2020

how to export csv file checkbox value into table in rails?

I want to checkbox value with csv file.I was tried under code

student.rb def self.to_csv attributes = %w{id status email temp_registration_date full_name full_name_kana main_registration_date email2 postal_code1 postal_code2 address1 address2 tel_main tel_sub sex school_type school_name school_name_initial department_name faculty_type graduation_month industry_id industry_most_id occupation_id occupation_most_id desired_work_region_code club_flg school_club_name school_club_type club_name lab_name major_field research_subject_title research_subject_summary interested_companies personal_summary how_known how_known_other mail_magazine_flg}

CSV.generate(headers: true) do |csv|
csv << attributes

all.each do |student|
    
    csv << [student.id,student.status,
 student.sex, if (student.school_type == 1)
    大学
 elsif (student.school_type == 2)
    大学院(修士)
 elsif (student.school_type == 3)
    大学院(博士)
 elsif (student.school_type == 4)
    短大
 elsif (student.school_type == 5)
    専門学校
 elsif (student.school_type == 6)
    高専
 end]
end
end

Correct Installation of Google Analytics on Ruby on Rails

I have a friend who has a developer working on this site: https://www.cannasaver.com/

When I access different pages on the site the UA code seems to duplicate over and over again according to the Google Tag Manager extension.

enter image description here

The developer is saying this is normal implementation and there there is nothing wrong. However on the other sites they own such as this: http://cannapages.com/ -- this does not seem to be the case.

I am wondering if the Google Analytics code is correctly implemented on https://www.cannasaver.com/ -- Any help you have as to if it is correctly added or what to do to fix it would be great appreciated!

mardi 1 décembre 2020

Writing crawler in ruby

I am writing a crawler in ruby, for the movie section of bsvalue website. https://bsvalue.com/category/5f74877a50e0c79d5d58b8a4;categoryTitle=Movies I am able to get the json, but i don't have idea how to save/print that all the movies name , id, cast etc, one by one using parmas . Can anyone help me in this.

here is the starting of my code which gives me json response

require "net/http"

url = URI("https://blacksheepapi.com/app-v2/api/mobile/home/category/5f74877a50e0c79d5d58b8a4/with-videos?offset=0&limit=40")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Get.new(url)
request["authority"] = "blacksheepapi.com"
request["pragma"] = "no-cache"
request["cache-control"] = "no-cache"
request["accept"] = "application/json, text/plain, */*"
request["authorization"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjoiNWZhM2EzYWZmNmRhY2MxMjVkOTQ3ZDlmIiwidXNlclR5cGUiOjIsImlzUHJlbWl1bVVzZXIiOmZhbHNlfSwiaWF0IjoxNjA2NzMxMTAwLCJleHAiOjE2MDkzMjMxMDB9.gv7iOF8s6aKBqiTMw1q-mdkxRjnfPnivuG4orBg2T0c"
request["user-agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36"
request["origin"] = "https://bsvalue.com"
request["sec-fetch-site"] = "cross-site"
request["sec-fetch-mode"] = "cors"
request["sec-fetch-dest"] = "empty"
request["referer"] = "https://bsvalue.com/"
request["accept-language"] = "en-GB,en-US;q=0.9,en;q=0.8"

response = https.request(request)
puts response.read_body

json = JSON.parse(response.body)

This is the json response I'm getting

    "isVisible" => true,
    "isDeleted" => false,
    "videoIds" => [{
        "isPremiumVideo" => false,
        "ageLimit" => 6,
        "_id" => "5fa01e17d7f2c12af4b03cf8",
        "title" => "Anjaneya",
        "images" => {
            "_id" => "5fb3b34f367224583e2f1ff4", "mobileBannar" => "5fa01e17d7f2c12af4b03cf8/assets/450_270.jpg?160561236759778053", "mobileThumbMedium" => "5fa01e17d7f2c12af4b03cf8/assets/370_500.jpg?160561236759790246", "tvDetailBannar" => "5fa01e17d7f2c12af4b03cf8/assets/1280_720.jpg?160561236759773244", "videoLogo" => "5fa01e17d7f2c12af4b03cf8/assets/600_200.png?160561236759760443", "posterUrl" => "5fa01e17d7f2c12af4b03cf8/assets/video-poster.jpg?160561236759725158"
        },
        "cast" => "Ajith Kumar, Meera Jasmine, Raghuvaran, Seetha, Jaya Prakash Reddy.",
        "categoryId" => "5f74877a50e0c79d5d58b8a4",
        "description" => "ACP Paramaguru (Ajith Kumar) is an efficient police officer who fights with the scum of the society. He later masquerades as a thief to infiltrate into the underworld. The bad guys are surprised to find that Paramguru is the ACP and is out to get them, so they all gang up against him. In this process, a thrilling encounter takes place between the good and the evil. Paramaguru is helped in his fight against injustice by Divya (Meera Jasmine), who falls in love with him.\n\nAnjaneya is a 2003 Indian Tamil-language action film directed by N. Maharajan. ",
        "miniPreviewUrl" => "5fa01e17d7f2c12af4b03cf8/assets/mini_preview.mp4",
        "sourceVideoQuality" => "1080p",
        "timeCode" => "2hr 54min 18sec",
        "videoType" => "ORIGINAL"
    }, {
        "isPremiumVideo" => false,
        "ageLimit" => 6,
        "_id" => "5fa29daad7f2c12af4b0adba",
        "title" => " Agni Natchathiram",
        "images" => {
            "_id" => "5fb3b35c367224583e2f2d6b", "mobileBannar" => "5fa29daad7f2c12af4b0adba/assets/450_270.jpg?160561238048172958", "mobileThumbMedium" => "5fa29daad7f2c12af4b0adba/assets/370_500.jpg?160561238048143726", "tvDetailBannar" => "5fa29daad7f2c12af4b0adba/assets/1280_720.jpg?160561238048193416", "videoLogo" => "5fa29daad7f2c12af4b0adba/assets/600_200.png?160561238048128347", "posterUrl" => "5fa29daad7f2c12af4b0adba/assets/video-poster.jpg?160561238048142775"
        },
        "cast" => "Prabhu , Karthik , Amala",
        "categoryId" => "5f74877a50e0c79d5d58b8a4",
        "description" => "Agni Natchathiram (transl. Scorching Star) is a 1988 Indian Tamil-language action drama film written and directed by Mani Ratnam. The film stars Prabhu, Karthik, Amala and newcomer Nirosha, with Vijayakumar, Jayachitra, Sumithra, Tara, S. N. Lakshmi and G. Umapathy in pivotal roles. It revolves around two half-brothers who come into conflict with each other in their claim for legitimacy as sons of a common father.",
        "miniPreviewUrl" => "5fa29daad7f2c12af4b0adba/assets/mini_preview.mp4",
        "sourceVideoQuality" => "1080p",
        "timeCode" => "2hr 19min 23sec",
        "videoType" => "ORIGINAL"
    }, {
        "isPremiumVideo" => false,
        "ageLimit" => 6,
        "_id" => "5fa670c76785a54d2d96f9d5",
        "title" => " Vaanchinathan",
        "images" => {
            "_id" => "5fb3b365367224583e2f3968", "mobileBannar" => "5fa670c76785a54d2d96f9d5/assets/450_270.jpg?16056123899617075", "mobileThumbMedium" => "5fa670c76785a54d2d96f9d5/assets/370_500.jpg?160561238996146991", "tvDetailBannar" => "5fa670c76785a54d2d96f9d5/assets/1280_720.jpg?160561238996144346", "videoLogo" => "5fa670c76785a54d2d96f9d5/assets/600_200.png?160561238996173272", "posterUrl" => "5fa670c76785a54d2d96f9d5/assets/video-poster.jpg?160561238996137035"
        },
        "cast" => "vijaykanth , ramyakrishnan",
        "categoryId" => "5f74877a50e0c79d5d58b8a4",
        "description" => "Vanchinathan (Vijayakanth) is naturally the supercop who has been transferred from Gujarat. He is someone who is not averse to using the law in his own ways by killing someone and picking a suitable alibi, as long as the person is evil and will not be punished by the law.",
        "miniPreviewUrl" => "5fa670c76785a54d2d96f9d5/assets/mini_preview.mp4",
        "sourceVideoQuality" => "1080p",
        "timeCode" => "2hr 47min 55sec",
        "videoType" => "ORIGINAL"
    }, {
        "isPremiumVideo" => false,
        "ageLimit" => 6,
        "_id" => "5fa6719d6785a54d2d96f9d8",
        "title" => " Periyanna",
        "images" => {
            "_id" => "5fb3b370367224583e2f46c3", "mobileBannar" => "5fa6719d6785a54d2d96f9d8/assets/450_270.jpg?160561240070856606", "mobileThumbMedium" => "5fa6719d6785a54d2d96f9d8/assets/370_500.jpg?160561240070824901", "tvDetailBannar" => "5fa6719d6785a54d2d96f9d8/assets/1280_720.jpg?160561240070872441", "videoLogo" => "5fa6719d6785a54d2d96f9d8/assets/600_200.png?160561240070832853", "posterUrl" => "5fa6719d6785a54d2d96f9d8/assets/video-poster.jpg?160561240070845895"
        },
        "cast" => "surya , meena",
        "categoryId" => "5f74877a50e0c79d5d58b8a4",
        "description" => "periyana",
        "miniPreviewUrl" => "5fa6719d6785a54d2d96f9d8/assets/mini_preview.mp4",
        "sourceVideoQuality" => "1080p",
        "timeCode" => "2hr 22min 42sec",
        "videoType" => "ORIGINAL"
    }, {
        "isPremiumVideo" => false,
        "ageLimit" => 6,
        "_id" => "5fa924d16785a54d2d96fd64",
        "title" => "Villain",
        "images" => {
            "_id" => "5fb3b37b367224583e2f534c", "mobileBannar" => "5fa924d16785a54d2d96fd64/assets/450_270.jpg?160561241118737975", "mobileThumbMedium" => "5fa924d16785a54d2d96fd64/assets/370_500.jpg?160561241118769411", "tvDetailBannar" => "5fa924d16785a54d2d96fd64/assets/1280_720.jpg?160561241118738963", "videoLogo" => "5fa924d16785a54d2d96fd64/assets/600_200.png?160561241118799290", "posterUrl" => "5fa924d16785a54d2d96fd64/assets/video-poster.jpg?160561241118758637"
        },
        "cast" => " Ajith & Meena,Kiran. Sujatha, FEFSI Vijayan, Karunaas , Ramesh Khanna",
        "categoryId" => "5f74877a50e0c79d5d58b8a4",
        "description" => "\nVillain is a 2002 Indian Tamil-language action masala film written and directed by K. S. Ravikumar and produced by S. S. Chakravarthy",
        "miniPreviewUrl" => "5fa924d16785a54d2d96fd64/assets/mini_preview.mp4",
        "sourceVideoQuality" => "1080p",
        "timeCode" => "2hr 44min 36sec",
        "videoType" => "ORIGINAL"
    }],```

Crawler in ruby

I am writing a crawler in ruby, for the movie section of bsvalue website. https://bsvalue.com/category/5f74877a50e0c79d5d58b8a4;categoryTitle=Movies I am able to get the json, but i don't have idea how to save/print that all the movies name , id, cast etc, one by one using parmas . Can anyone help me in this.

here is the starting of my code which gives me json response

require "net/http"

url = URI("https://blacksheepapi.com/app-v2/api/mobile/home/category/5f74877a50e0c79d5d58b8a4/with-videos?offset=0&limit=40")

https = Net::HTTP.new(url.host, url.port);
https.use_ssl = true

request = Net::HTTP::Get.new(url)
request["authority"] = "blacksheepapi.com"
request["accept"] = "application/json, text/plain, */*"
request["authorization"] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkYXRhIjp7ImlkIjoiNWZhYjk0NmIxZmVmZWQxN2I1Njc5ZWY4IiwidXNlclR5cGUiOjIsImlzUHJlbWl1bVVzZXIiOmZhbHNlfSwiaWF0IjoxNjA2NzMxMTgzLCJleHAiOjE2MDkzMjMxODN9.bgE8acYdOz5E7pqGLfOEP9D-No8AhJzj_ruYtygLkRU"
request["user-agent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
request["origin"] = "https://bsvalue.com"
request["sec-fetch-site"] = "cross-site"
request["sec-fetch-mode"] = "cors"
request["sec-fetch-dest"] = "empty"
request["referer"] = "https://bsvalue.com/"
request["accept-language"] = "en-GB,en-US;q=0.9,en;q=0.8"
request["if-none-match"] = "W/\"7b13-8sXFO/kqq7iWIQEBPNiEsg35CNQ\""

response = https.request(request)
puts response.read_body

json = JSON.parse(response.body)

lundi 30 novembre 2020

Could not run the `identify` command. Please install ImageMagick

I am using Paperclip and getting this error on the deployed site, not on my local server. And that's why it is becoming more difficult for me to get out of this.

A Paperclip::Errors::CommandNotFoundError occurred in images#update:
enter code hereCould not run the `identify` command. Please install ImageMagick.

I have tried these solutions but was not able to fix this (For ubuntu):

  1. Ran apt-get install imagemagick
  2. I don't use brew. So, won't be able to use brew install imagemagick
  3. Added and deployed these lines to paperclip_options.yml

:image_magick_path: '/opt/ImageMagick/bin' :command_path: '/opt/ImageMagick/bin'

Can anyone suggest how to resolve this error?

vendredi 27 novembre 2020

View action should show same response which I get on form submission

I have registration form , once I have submit that form , I was getting some response. I want to show same response on view action. Currently, I have registration page which have two tabs, one is for registration form and other is for post register activity form.where second tab is disabled till I have submitted the registration form. I am able to submit a form and getting response as well, now I want show same response on view action, How should I achieve that in rails web project ? How should my routes work in that case ?

Match request URL params with rails routes via recognize_path

I want to check if any incoming request actually exists in routes.rb as an entry via recognize_path like this

def path_exists?(path)
  Rails.application.routes.recognize_path(path)
  true
  rescue
   false
end

This works for most URLs but if the URL has a parameter, then it fails to recognize it.

Example:

In routes.rb, say I have an entry like this

put "foo/bar/:param" => "foo#bar"

and the incoming request URL is of the form /foo/bar/5

Then the function recognize_path doesn't recognize the URL as the value of the parameter is 5 but it is matched with :param

How do I match requests that have parameters to their entries in routes.rb using recognize_path or any other similar function?

Reason

I'm filtering out malicious attempts to hit the server using random URLs like /dump.sql.tar.gz, /conf.xz, etc using the gem rack::attack and throttling requests whose URLs are not a part of routes.rb. Hence the above problem.

Ruby on Rails - Criteria - Mongoid - where condition with 2 by 2 columns

I'm working with RoR + MongoDB (Mongoid) and I need to apply a filter using or condition by 2 columns.

I saw some recommendations like this one but didn't work.

query = query.where(name: /#{attributes[:name]}/i).or(query.where(email: /#{attributes[:email]}/i))

If I use this one, looks like the or will be applied for all conditions:

query = query.where(name: /#{attributes[:name]}/i).or(email: /#{attributes[:email]}/i)

Anyone has any suggestion?

jeudi 26 novembre 2020

Get this "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" combination for ruby

I have this java code for encryption and decryption, which I want to change/convert to Ruby code. I looked up in OpenSSL gem but dint find the "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" combination available for ruby. How do I implement it?

public class EncryptDecryptService {
    
    public String encryptRequestObject(RequestObject requestObject) throws UnsupportedEncodingException, FileNotFoundException, CertificateException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        PublicKey publicKey = getPublicKey(requestObject.getKeyFilename());
        byte[] message = requestObject.getString().getBytes("UTF-8");
        byte[] secret = encrypt(publicKey, message);
        return Base64.encodeBase64String(secret);
    }
    
    public String decryptRequestObject(RequestObject requestObject) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        PrivateKey privateKey = getPrivateKey(requestObject.getKeyFilename(), requestObject.getKeyPassword());
        byte[] cipherText = Base64.decodeBase64(requestObject.getString());
        byte[] decrypted = decrypt(privateKey, cipherText);
        return new String(decrypted, "UTF-8");
    }
    
    private PublicKey getPublicKey(String filename) throws FileNotFoundException, CertificateException {
        FileInputStream fin = new FileInputStream(filename);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) factory.generateCertificate(fin);
        PublicKey publicKey = certificate.getPublicKey();
        return publicKey;
    }
    
    private PrivateKey getPrivateKey(String filename, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
        FileInputStream fin = new FileInputStream(filename);
        KeyStore ks = KeyStore.getInstance("pkcs12");
        ks.load(fin, password.toCharArray());
        String str = ks.aliases().nextElement();
        PrivateKey privateKey = (PrivateKey) ks.getKey(str, password.toCharArray());
        return privateKey;
    }
    
    private byte[] encrypt(PublicKey key, byte[] plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(plainText);
    }
    
    private byte[] decrypt(PrivateKey key, byte[] cipherText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }
}

mercredi 25 novembre 2020

Find records have count of association > n

class PurchaseOrder < ApplicationRecord
  has_many :purchase_order_materials 
end 
class PurchaseOrderMaterial < ApplicationRecord
  belongs_to :purchase_order
  belongs_to :material
end

I have this query:

PurchaseOrderMaterial
  .includes(:purchase_order, :material)
  .where("purchase_orders.provider_id IS NULL AND purchase_orders.status = ? 
          AND (purchase_orders.is_waiting != ? 
               OR purchase_orders.is_waiting IS NULL)", 
         PurchaseOrder.possibleStatus.first, true)

All i want it's filter results to purchase_order.purchase_order_materials.count > 1. Some way to achieve it?

mardi 24 novembre 2020

Weird time.beginning_of_month rails 3 behavior

I am working on this query:

Student.where(created_at: time.beginning_of_month..time). Let's say the time here is: `15/10/2020 00:00:00`

I thought this is supposed to return the created students from 1/10/2020 00:00:00 to 15/10/2020 00:00:00 because time.beginning_of_month returns 1/10/2020 00:00:00

However, it returns me the created students from 30/09/2020 22:00:00 to 15/10/2020 00:00:00

I have checked with other months and I get the same results. Somehow, it always returns me the records starting from the last day of the previous month, not the first day of the current month

I am using Rails 3.2.2 and Ruby 2.1.5

samedi 21 novembre 2020

Gems are not found inside Docker container After sourcing RVM path

scenario1

So the problem I am facing like after building the docker images. If I am going inside the docker container and doing GEM_PATH=$GEM_HOME gem list it is not showing all the gems installed at the time of building the image. it is showing only a few gems.

scenario2

If I am not sourcing the RVM path inside the Dockerfile. Then If I am going inside the docker container and doing GEM_PATH=$GEM_HOME gem list then it is showing all the gems.

Can anyone please explain to me why this is happening and how I should install and source RVM? So I can see all the gems inside the container. Basically, I want the scenario1 should work. Thanks

Below is my Dockerfile

RUN apt-get update -qq && apt-get install -y sudo && apt-get install -y build-essential && apt-get install -y apt-utils && apt-get install -y git
RUN gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB && \curl -sSL https://get.rvm.io | sudo bash -s stable --ruby && echo 'source /usr/local/rvm/scripts/rvm' >> /etc/bash.bashrc
RUN /bin/bash -l -c 'gem install bundler -v 1.17.3'
RUN /bin/bash -l -c 'gem install rails --version=5.2.4.1'
WORKDIR /app
RUN bundle config build.nokogiri --use-system-libraries
RUN bundle config set path 'vendor/bundle'
COPY Gemfile Gemfile.lock ./
ARG SSH_KEY
# Make ssh dir
RUN mkdir /root/.ssh/
# Copy ssh
RUN echo "$SSH_KEY" > /root/.ssh/id_rsa && \
   chmod 0600 /root/.ssh/id_rsa
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts
RUN bundle install
COPY . ./
EXPOSE 80:80
CMD rails s -p 80 -b '0.0.0.0' -e qa```


vendredi 20 novembre 2020

Create multiple objects while seeding in Ruby on Rails

I have the following seed file that creates many animals which are then added to the animal_store object

animal_store_seeder:

animal1 = create(:animal)
animal2 = create(:animal)
animal3 = create(:animal)

create(
  :animal_store,
  json: {
    "animals": {
      animal1.id=> {
       }, 
      animal2.id =>{
    }
   ... 
  }
}    

So far this works. However, I want to create a store with at least 20 animals. I don't think creating each variable is the correct way to go. Is there a better way to instantiate more animals and adding them to the animal_store without having to create them one at a time?

mercredi 18 novembre 2020

rspec parallel tests without database

I'm using RSpec as an API test harness that does not have a database during testing, and would like to parallelize the runs. I've tried https://github.com/grosser/parallel_tests but the rake task fails when there is no database with Don't know how to build task "'parallel:spec'".

I then moved to the deprecated https://github.com/yuku/parallel-rspec which worked, but it's not passing the arguments I've been using to filter tests correctly.

For example, if I had 10 tests, 2 of which had metadata feature=search would historically run:

bundle exec rspec --tag feature:search

And only those 2 tests would be run.

Now running

`` bundle exec parallel-rspec spec --tag feature:search

still runs all 10 tests.

How can I split up my specs into parallel runs while still preserving the ability to filter by metadata?

mardi 17 novembre 2020

No such file or directory - java rake aborted

I'm having a rails project running properly on my local machine but when I deploy it on heroku I get the error below. I seem not to understand what I'm not doing well. Initially, the project was using gem bootstrap-will_paginate, I removed it and switched to gem bootstrap. Right now as I have mentioned above, locally, the project is running as expected but when I try to deploy to heroku, I run into the error below. Any assistance will be highly appreciated. Thanks

       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-6128dd44fed3a046ff8d835d677e0a837c70c64dc1c944b7edfde04eb8d8b879.eot
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-6128dd44fed3a046ff8d835d677e0a837c70c64dc1c944b7edfde04eb8d8b879.eot.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-f9853ad337d523c0b35fe7ac306268a7035ce0ff7624710ed8b39c2b88b20a33.eot
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-f9853ad337d523c0b35fe7ac306268a7035ce0ff7624710ed8b39c2b88b20a33.eot.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-e0e3c4af28348d721f8af603595c15d273a56f2b03392f9a413255fe5635f536.eot
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-e0e3c4af28348d721f8af603595c15d273a56f2b03392f9a413255fe5635f536.eot.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-e2749cb24a77208abdd9fda35f0d14f091948c44d21f977c8048a3b13e4beccb.svg
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-e2749cb24a77208abdd9fda35f0d14f091948c44d21f977c8048a3b13e4beccb.svg.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-d42a64dc349a98075e8be12587943f2bd52065a8bb18960d7dc7390b535117e0.svg
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-d42a64dc349a98075e8be12587943f2bd52065a8bb18960d7dc7390b535117e0.svg.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-1a46e780ce5beb6507d62af8b20a92b33c8f042e87c612f4bbf8330bfc353419.svg
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-1a46e780ce5beb6507d62af8b20a92b33c8f042e87c612f4bbf8330bfc353419.svg.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-404d6083193e569bc5c28c7b1bc0e13ece80c6e0f5a50ad8e9633f48f3c09155.ttf
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-404d6083193e569bc5c28c7b1bc0e13ece80c6e0f5a50ad8e9633f48f3c09155.ttf.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-5e811f0b32d488b9a183b77cfc7ac1ef44b3ea7aaed014e83975dfe597d221f6.ttf
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-5e811f0b32d488b9a183b77cfc7ac1ef44b3ea7aaed014e83975dfe597d221f6.ttf.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-2caded242c04139761742fe0cda7f6592df1b6686857532c8a7c2e2536b976e4.ttf
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-2caded242c04139761742fe0cda7f6592df1b6686857532c8a7c2e2536b976e4.ttf.gz
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-a0375c054a0041bd58e2a0bf7fa3df7c3904bfc4f790fd24e32ff3ee70fd0eef.woff
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-6799c999e422710f40f70a60a6138fc38106226c44d7bd1b1023f5bb65befef9.woff
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-aab971ade1633ab836222074ceae0aad8a082d900908f27491b221d6e83998ca.woff
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-brands-400-71b3ce72680f4183d28db86b184542051fd533bb1146933233e4f6a20cf98cba.woff2
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-regular-400-ce20ed8a323117c8a718ff1ddc6dabb997373b575a8e896f2bf02b846c082c9d.woff2
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/font-awesome/fa-solid-900-6b555920e358f8a25a422988b448615c33bcccb4f932e8331cebfc8e2a737fc7.woff2
       2020-11-17 08:37:42 INFO -- Writing /tmp/build_52cf5ac5_/public/assets/flut-086c6ba8919955ef94b7c049b9870b6fd5026b55ea17d8659d1b5e26c74c6b1c.png
       /tmp/build_52cf5ac5_/bin/rake: No such file or directory - java
       rake aborted!
       Command 'java -jar /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/../yuicompressor-2.4.8.jar --type css --charset utf-8 /tmp/yui_compress20201117-409-dud2hb' returned non-zero exit status
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/compressor.rb:106:in `block in compress'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/compressor.rb:141:in `streamify'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/yui-compressor-0.12.0/lib/yui/compressor.rb:86:in `compress'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/yui_compressor.rb:49:in `call'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/yui_compressor.rb:28:in `call'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:75:in `call_processor'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:57:in `block in call_processors'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:56:in `reverse_each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/processor_utils.rb:56:in `call_processors'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:134:in `load_from_unloaded'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:60:in `block in load'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:317:in `fetch_asset_from_dependency_cache'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/loader.rb:44:in `load'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:20:in `block in initialize'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/cached_environment.rb:47:in `load'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:66:in `find_asset'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/base.rb:73:in `find_all_linked_assets'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/manifest.rb:142:in `block in find'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:114:in `block (2 levels) in logical_paths'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:228:in `block in stat_tree'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:212:in `block in stat_directory'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:209:in `each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:209:in `stat_directory'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/path_utils.rb:227:in `stat_tree'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:105:in `each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:105:in `block in logical_paths'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:104:in `each'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/legacy.rb:104:in `logical_paths'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/manifest.rb:140:in `find'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/sprockets/manifest.rb:186:in `compile'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-rails-3.2.2/lib/sprockets/rails/task.rb:67:in `block (3 levels) in define'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-3.7.2/lib/rake/sprocketstask.rb:147:in `with_logger'
       /tmp/build_52cf5ac5_/vendor/bundle/ruby/2.6.0/gems/sprockets-rails-3.2.2/lib/sprockets/rails/task.rb:66:in `block (2 levels) in define'
       Tasks: TOP => assets:precompile
       (See full trace by running task with --trace)
 !
 !     Precompiling assets failed.
 !
 !     Push rejected, failed to compile Ruby app.
 !     Push failed

Any assistance will be highly welcome

lundi 16 novembre 2020

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "courses" WHERE "courses"."Id"

routes.rb
    Rails.application.routes.draw do
          get "students" => "students#index"
          get "students/new" => "students#new"
          post "students" => "students#create"
        
          get "courses" => "courses#index"
          get "courses/new" => "courses#new"
          post "courses" => "courses#create"
        
          get "students/:id" => "students#show"
          get "courses/:id/students" => "courses#students"
          get "courses/:id/assignments" => "courses#assignments"
          get "courses/:id/assignments/new" => "assignments#new"
          post "courses/:id/assignments" => "assignments#create"
        
          get "courses/:id/edit" => "courses#edit"
          patch "courses/:id" => "courses#update"
          delete "courses/:id" => "courses#destroy"
        
        get "students/:id/edit" => "students#edit"
        patch "students/:id" => "students#update"
        delete "students/:id" => "students#destroy" 
        end 

CourseController.rb
        class CoursesController < ApplicationController
        def index
        @courses = Course.all
        end
        
        def new
        end
        
        def create
        course = Course.new(course_params)
        if course.save
        redirect_to "/courses"
        else
        flash[:errors] = course.errors.full_messages
        redirect_to "/courses/new"
        end
        end
        
        def students
        @students = Course.find(params[:id]).students
        end 
        
        def assignments
        @assignments = Course.find(params[:id]).assignments
        end
        
        def edit
        @course = Course.find(params[:id])
        end
        
        def update
        course = Course.find(params[:id])
        if course.update(course_params)
        redirect_to "/courses"
        else
        flash[:errors] = course.errors.full_messages
        redirect_to "/courses/#{course.id}/edit"
        end
        end
        
        def destroy
        @assignments = Course.find(params[:id])
        @assignments.destroy                      //This line is showing me an error
        redirect_to "/courses/new"
        end
        
        private
        def course_params`enter code here`
        params.require(:course).permit(:title, :professor, :room)
        end
        end

My delete function is not working in this code. When I am trying to run this code it shows the following error what is show in the title. please can someone help me to solve this question thank you. I will also highlight the line whatever line shows the error it is just one line. I do not I think it coding thing is right. but, I guess I am missing some inside the code or probably on routes.rb

jeudi 12 novembre 2020

rake aborted when i do rake db:setup

when i do rake db:setup the rake it's aborted and i don't know why...................... because postgresql is running this is the output of postgreql

fabian@Inna-marley:~$ sudo su - postgres [sudo] contraseña para fabian: postgres@Inna-marley:~$ psql psql (13.0 (Ubuntu 13.0-1.pgdg20.04+1)) Digite «help» para obtener ayuda.

postgres=#

this is the output on my terminar

rake db:setup
rake aborted!
ArgumentError: Write key must be initialized
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics/client.rb:319:in `check_write_key!'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics/client.rb:28:in `initialize'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics.rb:14:in `new'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/analytics-ruby-2.0.13/lib/segment/analytics.rb:14:in `initialize'
/home/fabian/rails-backend/config/initializers/analytics_ruby.rb:3:in `new'
/home/fabian/rails-backend/config/initializers/analytics_ruby.rb:3:in `<main>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:59:in `load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:285:in `block in load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:257:in `load_dependency'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:285:in `load'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:657:in `block in load_config_initializer'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/notifications.rb:170:in `instrument'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:656:in `load_config_initializer'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:614:in `block (2 levels) in <class:Engine>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:613:in `each'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/engine.rb:613:in `block in <class:Engine>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:32:in `instance_exec'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:32:in `run'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:61:in `block in run_initializers'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:50:in `each'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:50:in `tsort_each_child'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/initializable.rb:60:in `run_initializers'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/application.rb:361:in `initialize!'
/home/fabian/rails-backend/config/environment.rb:5:in `<main>'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:23:in `block in require_with_bootsnap_lfi'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:92:in `register'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:22:in `require_with_bootsnap_lfi'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bootsnap-1.5.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:31:in `require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:291:in `block in require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:257:in `load_dependency'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/activesupport-5.2.2.1/lib/active_support/dependencies.rb:291:in `require'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/application.rb:337:in `require_environment!'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/railties-5.2.2.1/lib/rails/application.rb:520:in `block in run_tasks_blocks'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/bugsnag-6.18.0/lib/bugsnag/integrations/rake.rb:20:in `execute'
/home/fabian/.rvm/gems/ruby-2.6.6/gems/rake-13.0.1/exe/rake:27:in `<top (required)>'
/home/fabian/.rvm/gems/ruby-2.6.6/bin/ruby_executable_hooks:24:in `eval'
/home/fabian/.rvm/gems/ruby-2.6.6/bin/ruby_executable_hooks:24:in `<main>'
Tasks: TOP => db:setup => db:schema:load_if_ruby => db:create => db:load_config => environment
(See full trace by running task with --trace)

Issue with the build for has_one association

I get getting an error every time I try to save a model with a has_one association, and I am not sure what I am doing wrong. Here is the error message and code below enter image description here

user.rb

  has_one :user_options

user_option.rb

 belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :user_options
    )

user_options_controller.rb

def create
    @user = current_user
    @user_option = current_user.build_user_option(user_option_params)
    respond_to do |format|
      if @user_option.save
        format.html { redirect_to @user_option, notice: 'User option was successfully created.' }
        format.json { render :show, status: :created, location: @user_option }
      else
        format.html { render :new }
        format.json { render json: @user_option.errors, status: :unprocessable_entity }
      end
    end
  end

Any help would be great!

mercredi 11 novembre 2020

Is it possible to use onchange on base select option

Is there a way to use a submit onchange on this select option. I know I can do it on the <% f.select%> one with :onchange => 'this.form.submit()'), but I can't find any documentation on how to do it on this select statement.

<%= form_for(@profile_option, remote: true) do |form| %>

    <div class="form-group" id="profile_options_budgetid" >
      <div class="h7 text">Select Budget to Show</div>
         <select class="custom-select" name="profile_options[budget_id]" id="profile_options_budgetid">
           <option disabled value="" selected hidden>Please Select</option>
           <% Budget.where(user_id:current_user).each do |budget| %>
           <option value=<%= budget.id %>> Budget: <%= budget.month %> <%= budget.year %>
            </option>
                                            
             <% end %>
         </select>
      </div>
<% end %>

mardi 10 novembre 2020

rake db:seed error- uninitialised constant

I came across the following error when running rake db:seed:

Running via Spring preloader in process 26002 rake aborted! NameError: uninitialized constant Location /mnt/c/Users/raeye/AppData/Local/Packages/CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc/LocalState/rootfs/home/cpde/weatherapp/db/seeds.rb:9:in <main>' -e:1:in ' Tasks: TOP => db:seed (See full trace by running task with --trace)

Seed file:

l = Location.create(name: "New York City")
l.recordings.create(temp: 32, status: "cloudy")
l.recordings.create(temp: 28, status: "rainy")
l.recordings.create(temp: 30, status: "sunny")
l.recordings.create(temp: 31, status: "rainy")

Location:

class Location < ApplicationRecord
  has_many :recordings
end

Recording:

class Recording < ApplicationRecord
  belongs_to :location
end

timestamp files

class CreateLocations < ActiveRecord::Migration[6.0]
  def change
    create_table :locations do |t|
      t.string :name

      t.timestamps
    end
  end
end

class CreateRecordings < ActiveRecord::Migration[6.0]
  def change
    create_table :recordings do |t|
      t.references :location, null: false, foreign_key: true
      t.integer :temp
      t.string :status

      t.timestamps
    end
  end
end

I'm thinking that it could due to naming convention error, can anyone shed some light on this?

Having trouble using unless current_page? to hide a button

I'm trying to hide this button from all the show pages of the Rooms model. I have an array of the rooms id stored in @extra but whenever I try to use current_page?(room_path(@extra)) it doesn't work, but when I specify the id, for example, current_page?(room_path(6)) it works and hides the button. What am I doing wrong?

<% unless current_page?(controller: 'rooms') || current_page?(room_path(@extra))%>

   <button onclick="myFunction()" class="button btn btn-light bg-white rounded-pill shadow-sm px-4 mb-4" 
   style="vertical-align:middle">
   <span>
      <small class="text-uppercase font-weight-bold"> Nav-bar Toggle</small>
   </span>
</button>

      <% end %>

How do I hide button text with CSS?

I'm trying to hide the text Following when a user hovers over a button. I don't really have too much experience with CSS and am having difficulties doing this.

This is my button

<span>
   <%= link_to  'Following', follow_url(found), method: :delete, 
                class: "btn unfollow-button", id: 'unfollow-button', 
                data: { confirm: 'Are you sure?' } 
    %>
</span>

Below is the application.scss

.unfollow-button {
  width: 100px; /* set a width so it doesnt change upon hover */
  content: 'Following';
  border-color: #bd2b2b;
  background-color: #140d6d;
  color: white;
  margin-left: 20px;
  &:visited, &:focus, &:hover {
    content: 'Following';
    border-color: #FF0000;
    background-color: #FF0000;
    color: white;
  }
  
}
.unfollow-button:hover span {
  display:none
}
.unfollow-button:hover:before {
  content:" Unfollow ";
}

Right now the button is appending the new content Unfollow to the front of the button, but not removing the old content

So the button goes from Following to Unfollow Following instead of the desired result of Following to UnFollow

Any help would be greatly appreciated. Thanks!

dimanche 8 novembre 2020

Can I replace (Date.current - created_at.to_date).to_i <= number_of_days with number_of_days.days.ago.to_date? Is it a good idea?

In my models/book.rb I have this

  def created_since?(number_of_days)
    (Date.current - created_at.to_date).to_i <= number_of_days
  end

That is used in view files like

<% if @book.created_since?(30) %>

Can I optimize it editing with something like this?

  def created_since?(number_of_days)
    number_of_days.days.ago.to_date
  end

Is it a good idea? will it work the same?

samedi 7 novembre 2020

Need a block of ruby code explained - or at least what I need to do to look it up

I'm a programmer, but I don't know ruby and/or ruby on rails at all. All I need to do is skip this validation check - have it return true - or return whatever value it returns if the hash is unique. I can't find explanations for the use of : nor :on Can anyone either explain to me what is happening here, or tell me how I can look up the pertinent symbols/terms?

class Stl < ApplicationRecord
  before_validation :compute_hash
  validates_uniqueness_of :md5hash, :on => :create

  mount_uploader :file, StlUploader
  belongs_to :product


  def compute_hash
    self.md5hash = Digest::MD5.hexdigest(self.file.read)
  end

end

vendredi 6 novembre 2020

How can I scrape a Website with onClick event listener using Nokogiri

I am trying to scrape a website using Nokogiri and download documents thats are posted on the website. I can scrape other websites like this one: Matatiela Website and get the documents from it. But when I try to scrape this website: Mbhashe Website I can't get the documents because I have to first triger the onclick event in order to get to the document.

The problem now, I don't know how to triger the onclick event in order to get to the document. I have tried this code that I worked on with my friend but it didn't work:

if url.include?('http://www.alfredduma.gov.za/bids-tender-notices/')
   file = anchor['onclick'].to_s.gsub("location.href=","").gsub(";return false;","").gsub("'","")
   f = mech.get(file)
   fileNmae = f.header['content-disposition']
   fileNmae = fileNmae.match('"(.*?)"').andand[1].to_s
   fileNmae = municipalityName+ " -" +fileNmae.gsub("_"," ")
   downld(municipalityName,file,filepath,fileNmae,provinceName)
end

This code didn't work. But bellow is the code that is similar to the one i used to scrape Matatiela website but it's not working on the website of Mbhashe. Can you please help me because it does not return anything.

["https://www.mbhashemun.gov.za/procurement/tenders/","div.tb > div.tbrow > a","http://www.mbhashemun.gov.za","Mbhashe municipality","Eastern Cape"]

My Myfuction gets the css from this array.

if baseurl.include?('ttps://www.mbhashemun.gov.za/procurement/tenders/')
              
                            puts "downloading from mbhashemun"
                            parenturl = anchor['href']
                            puts parenturl
                            puts baseurl
                            tenderurl = parenturl
                          begin
                            if tenderurl.include?('http://www.mbhashemun.gov.za/web/2018/11/upgrade-and-maintenance-of-data-centre-for-a-period-of-three-03-years/')
                                   puts "the document is currently not available"
                            else
                                    puts tenderurl
                                    passingparentUrl = HTTParty.get(tenderurl)
                                    parsedparentUrl = Nokogiri::HTML(passingparentUrl)
                                    downloadtenderurl = parsedparentUrl.at_css('div.media div.media-body > div.wpfilebase-attachment > div.wpfilebase-rightcol > div.wpfilebase-filetitle > a')[:href]
                                    puts downloadtenderurl
                                    bean =  downloadtenderurl
                                    puts bean
                                    myfunction =  bean.split('/').last
                                    puts Myfunction
                                    if File.exists?(File.join('public/uploads', Myfunction))
                                       puts "the file exist in upload folder and in the database already"
                                    else
                                       mech.pluggable_parser.default = Mechanize::Download
                                       mech.get(bean).save(File.join('public/uploads', monwai))
                                       Tender.create  municipality_name: municipalityName ,tender_description:Myfunction ,tender_document: Myfunction ,provincename: provinceName
                                    end
                               end
                            rescue Exception => e
                               puts e
                            end
                         end 

The code supposed to go throught the website and download the documents and save them on the public/uploads folder on the app.

Rails self reference one model with has_many

We want to achieve the following:

  1. Be able to compare 'Projects' with other (multiple) Projects.
  2. Save the comparison reference in the database.

In the past we did this by storing an array in the database like below:

t.string "comparisons", default: [], array: true

Now we are thinking about using another table - unless there is a better way?

Ideally something like this:

We already have this table:

|  projects |
|-----------|
| id | name |
| 1  | abc  |
| 2  | def  |
| 3  | ggg  |
| 4  | fff  |

We want to create another table similar to this:

|       project_comparisons     |
|-------------------------------|
| id | project_id | compared_id |
| 1  |     1      |      2      |
| 2  |     1      |      4      |
| 3  |     2      |      3      |
| 4  |     2      |      4      |

Where in the end we could do something like this:

Project.find(1).project_comparisons.each do |x|
  x.name
end

# Output:
'def'
'fff'

But we are getting lost in the relationship setup.

This is what we have so far:

rails g model ProjectComparison project:references compared:references

# Migration file (edited)
create_table :project_comparisons do |t|
  t.references :project, foreign_key: true
  t.references :compared
end


class Project
  has_many :project_comparisons
  has_many :projects, through: :project_comparisons
  # ... Here I think we need something in the line above?
end


class ProjectComparison
  belongs_to :project
end

This now has the the incorrect output. If we now iterate the example:

Project.find(1).project_comparisons.each do |x|
  x.name
end

# Output:
# aaa
# aaa

It should have been 'def' and 'fff'

Can I somehow specify that we want the 'compared_id' to get the correct Project, or are we on the wrong path here?

RSpec test module location

I am new to RSpec and I saw that in the sample the class tested is located in the lib folder. when 'require' class, it can directly import?(that is how I took it) the class from that folder. I tried require app/controllers/the_file_with_the_class_I_want_to_test and it says that it was not found. Should I copy and paste the file into the lib path?

lundi 2 novembre 2020

trying to solve /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError) led to bad interpreter: /usr/local/opt/python/bin/python2.7

  1. After a brew upgrade, I couldn’t run any of my Ruby on Rails apps anymore. I got this error message:

    : dlopen(/Users/ll/.rbenv/versions/2.6.2/lib/ruby/2.6.0/x86_64-darwin18/openssl.bundle, 9): Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (LoadError) Referenced from: /Users/ll/.rbenv/versions/2.6.2/lib/ruby/2.6.0/x86_64-darwin18/openssl.bundle Reason: image not found - /Users/ll/.rbenv/versions/2.6.2/lib/ruby/2.6.0/x86_64-darwin18/openssl.bundle

  2. So I tried

brew switch openssl 1.0.2t

solution sugests here https://stackoverflow.com/a/59184347/11410556 But couldn't find openssl 1.0.2t, my version was openssl@1.1 1.1.1h

  1. Then I tried

brew uninstall --ignore-dependencies openssl brew tap-new $USER/old-openssl brew extract --version=1.0.2t openssl $USER/old-openssl brew install openssl@1.0.2t ln -s /usr/local/Cellar/openssl@1.0.2t/1.0.2t /usr/local/opt/openssl

suggest here: https://stackoverflow.com/a/64479513/11410556. But when I ran

brew switch openssl 1.0.2t

I got this Error:

openssl does not have a version “1.0.2t” in the Cellar.
openssl’s installed versions
  1. So I went for this solution

    brew unlink openssl@1.1 brew link openssl@1.0.2t

And then get:

Warning: Refusing to link macOS provided/shadowed software: openssl@1.0.2t
If you need to have openssl@1.0.2t first in your PATH run:
 echo ‘export PATH=“/usr/local/opt/openssl@1.0.2t/bin:$PATH”’ >> ~/.zshrc
For compilers to find openssl@1.0.2t you may need to set:
 export LDFLAGS=“-L/usr/local/opt/openssl@1.0.2t/lib”
 export CPPFLAGS=“-I/usr/local/opt/openssl@1.0.2t/include”
For pkg-config to find openssl@1.0.2t you may need to set:
 export PKG_CONFIG_PATH=“/usr/local/opt/openssl@1.0.2t/lib/pkgconfig”  
  1. I ran the first choice :

    echo 'export PATH="/usr/local/opt/openssl@1.0.2t/bin:$PATH"' >> ~/.zshrc

restart my server and now I have

omz_urlencode:2: /usr/local/bin/pygmentize: bad interpreter: /usr/local/opt/python/bin/python2.7: no such file or directory (edited) 

Whatever I do.

  1. I'm not used to try things I don't understand and I think I went too far. I would be very grateful for any help to get out of this mess.

dimanche 1 novembre 2020

Error while installing ruby on rails asking zeitwork i do no how to proceed with this error

The error message while installing rails please help me to sort it out to learn ruby on rails

How to stop select statement from overwriting the other if they save to the same column

so I am trying to save one of these select statements depending on another select. I have both of these select statements hidden and if the previous select option is 1 goals is shown. If 2 is selected the budget is shown. But the problem is when I try to set the next value. The last select value overwrites the other. So if I select goals and try to save that value the budget select will overwrite it. What is the best way to stop this from happening?

<div class="form-group" id="goal_attachid" style="display: none;">
<%= form.label :"Select Goal to Attach" %>
   <select name="post[attachid]" id="goal_attachid">
    <option disabled value="" selected hidden>Please Select</option>
    <% Goal.where(user_id:current_user).each do |goal| %>
       <option value=<%= goal.id %>> Goal: <%= goal.title %></option>
    <% end %>
   </select>
  </div>

    <div class="form-group" id="budget_attachid" style="display: none;">
       <%= form.label :"Select Budget to Attach" %>
       <select name="post[attachid]" id="budget_attachid">
        <option disabled value="" selected hidden>Please Select</option>
        <% Budget.where(user_id:current_user).each do |budget| %>
           <option value=<%= budget.id %>> Budget: <%= budget.month %> <%= budget.year %>
        </option>
       <% end %>
  </select>
</div>

vendredi 30 octobre 2020

How to add a default value to sort: in query_type.rb

Existing code in query_type.rb:

def flags(program_id:, filter: {}, sort: {})
      program = Program.find(program_id)
      context[:auth].set_current_parent_program_id(program.id)
      flags = Report.joins(:participant).where(registrants: { program_id: program.id })
      Types::Programs::FlagsFilter.get_filtered(flags: flags, filter: filter, sort: sort)
 end

I am new to Ruby and the flags are coming in reverse order (ascending) and I want to set the default value to descending. I tried setting it like this:

def flags(program_id:, filter: {}, sort: { column: 'CREATED_AT', direction: 'DESCENDING' })
      program = Program.find(program_id)
      context[:auth].set_current_parent_program_id(program.id)
      flags = Report.joins(:participant).where(registrants: { program_id: program.id })
      Types::Programs::FlagsFilter.get_filtered(flags: flags, filter: filter, sort: sort)
 end

but I'm getting an error and my flags table is no longer rendering. Any suggestions?

jeudi 29 octobre 2020

Uppercase column names from MYSQL

Have an external MYSQL DB and I am connecting it to the ruby app. All the columns are changes to uppercase and when I try to query something it works but ruby gives an undefined method error when i try to call some field from the object like:

user = User.first works but when i do user.firstname it says undefined method firstname because the user object I get has firstname column as FIRSTNAME. How can I make it a case-incentive query so either i do user.firstname or user.FIRSTNAME it works?

i tried adding ActiveRecord::ConnectionAdapters::SQLServerAdapter.lowercase_schema_reflection = true into my cofig/initializers/activereport_sqlserver_adapter.rb but still no change.

mercredi 28 octobre 2020

Ng-repeat in angularjs with rails association

I am the beginner in angular js. I'm working on the project in which I have to use ng-repeat. In the backend, I have many to many self relationships(RoR). For example, I am using model A in rails for many to many self relations. Now my question is How should I use ng-repeat to show through table along with the model itself. I have used a single model using ng-repeat=" item in items" but this approach not good in this scenario. Please guide me in this regard thankyou.

(Relation Explanation) Suppose Model A has self-relation (many to many) with itself. I need model A to show some value through Model.something along with the attribute of model A through ng-repeat. We can easily use ng-repeat for i in Model A but i need rails associated object as well.

mardi 27 octobre 2020

When and how request sometimes found to be unverified. ruby on rails 3.2

#This is the method that defines the application behavior when a request is found to be unverified. #By default, Rails resets the session when it finds an unverified request.

  def handle_unverified_request
    reset_session
  end

I have seen this explanation at "https://ift.tt/3kGBNgw" now my question is when and how every request sometimes become unverified? how it was hapenning? and when.

thankyou, i have tried to search it but i have seen explanation so deep-technical hence i can understand in an easy way

Asset pipeline error when trying to use Gemoji Gem

I getting an error whenever I try to use the gemoji gem. Does anybody know how to fix it?

app/helpers/application_helper.rb

def emojify(content)
    h(content).to_str.gsub(/:([\w+-]+):/) do |match|
      if emoji = Emoji.find_by_alias($1)
        %(<img alt="#$1" src="#{image_path("emoji/#{emoji.image_filename}")}" style="vertical-align:middle" width="20" height="20" />)
      else
        match
      end
    end.html_safe if content.present?
  end
end

enter image description here

Conditional statement in Ruby on Rails

I'm working on Jira integration in my project. I wanted to add a condition to check if project_id is generated from the valid user account (same user account). If it is generated from valid user account then show the message Jira integration is successfulotherwise Jira integration is not successful.

This is the code that I'm using.

Jira.prototype.setJiraProject = function(projects) {
    var projectField = $("#project_id"),
      projectID = $("#project_id").val();
    projectField.find('option[data-type=jira-int]').remove();
    projects.map(function(el){
      if (projectID != el[0])
        projectField.append($('<option>', { 'data-type': 'jira-int', value: el[0], text: el[1]}));
    });
    projectField.attr('disabled', false).focus();
    showError('Jira integration is successful.', 'success');
  };

Is there anyway possible to achieve it?

Less/More option disappears on closing one notification (Ruby on Rails)

I'm writing a ROR code in which a notification at top will appear if transaction fails with Less/More option. But problem occurs when user closes one notification then Less/More option disappears for the other.

This is the code that I'm using

$(document).ready(function() {
    if ( $(window).width() < 1025 ) {
    var showChar = 20;
    var ellipsestext = "...";
    var moretext = "More";
    var lesstext = "Less";
    
    $('.confirm-account').each(function() {
        var content = $(this).html();
 
        if(content.length > showChar) {
 
            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);
 
            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
 
            $(this).html(html);
        }
    });
 
    $(".morelink").click(function(){
      $('.system-message').empty();
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
  }

Is there any way possible in which the Less/More option remains there even after closing one notification?

dimanche 25 octobre 2020

How do I print out model data without printing the array?

I know that this is basic, but I cannot figure it out for whatever reason.

I'm trying to return some model data and the majority of the time I return it with pluck, but pluck is returning an array. How do I return the value without the array?

<dd><%= Goal.where(id:post.attachid).pluck(:title) %></dd>

This is the code that I have and it is returning, for example, ["Computer"]

How do I just make it return Computer

jeudi 22 octobre 2020

Not sure how to convert this type of text content to valid HTML in Ruby view

I'm not sure exactly what this type of text is called but I am having a hard time getting to convert to valid HTML. Here is an example string

\ufffd\u0004\ufffd{\u003Cp\u003E\u003Ca href=\"https://magazine.com/lifestyle/grooming/url-of-article\"\u003E\u003Cimg src=\"Vp\u0000pwp-content/uploads/2020/08/Ph\u0005x\ufffd(\u0001.jpg\"\u003E\u003C/a\u003E\u003C/p\u003ELegend has it, Ernest Hemmingway once emerged from the Ugandan jungle after surviving two plane crashes brandishing a bunch of bananas and a bottle of gin. With a poorly bandaged arm, he reportedly quipped with a wry smile \ufffd\ufffd\ufffdMy luck, she is running very good.\ufffd\ufffd\ufffd [\ufffd\ufffd\ufffd]\u003Cbr\u003E\u003Cp\u003EVisit \u003C\ufffd\ufffd\u0001\ufffd\ufffd\u0001(Magazine!\ufffdX for the full post.\u003C/p\u003E"

I need to convert the output to be valid HTML. I can remove everything and make it readable text, but I need it to also contain the HTML elements.

Sidekiq memory leak issue

I am using sidekiq gem to move my heavy reporting jobs to background. The problem is that sidekiq does not release memory even after a job is completed and it is causing an ever increasing memory bloat, resulting in sidekiq restart after every 4-5 jobs. I have tried ActiveRecord::Base.uncached and even tried this in my application.rb - config.middleware.delete "ActiveRecord::QueryCache" but still no use. Even GC.start is not working. How do I clear memory after every job?

mardi 20 octobre 2020

Send data from view page to function in controller language ruby

I have a code html dropDowns with 2 option English And Arabicand a button Save

Code in view page :

<div class="box">
          
          <div class="label-field-pair">
              <label for="languages"><%= "Choose Language" %></label>
              <div class="text-input-bg">
              <select name="language" id="language">
              <option value="english">English</option>
              <option value="arabic">Arabic</option>
              </select>
              </div>
          </div>

         <div id="submit-button">
              <%= submit_tag "► #{t('save')}" %>
          </div> 
      </div>

When i choose 1 of option and click in save button i want to send data to fucntion in controller

Controller :

class LanguagesController < ApplicationController
  def save
    

    
  end
end

Function save only get data of option (English or Arabic) and update table language in database. Easy to me to update table but i don't know how to get data from view to function in controller.

Code in ruby

Ruby on rails Please give me the basics of using gem devise

I would like to create a simple login system as shown in this picture. I am currently practicing writing in Ruby on rails language, I will try to understand it and continue to work on it.

Please give me a detailed description. Thank you.

enter image description here

enter image description here

enter image description here

lundi 19 octobre 2020

Can't print data "name" ruby on rails

I am trying to print data from a object "root" to a table, everythink work fine but not printing this name i dont know why.

Code :

<% root = NameOfDatabase.find_by_student_id(student.id) %>
            <%  logger.info root.inspect %>
            <% if root.nil? %>
           <td class="col-4"> <% "-" %> </td>
           <%  else %>
           <td class="col-4"> <% root.name %> </td>
           <% end %>

Picture: View

Log file :

...  
#<Name**** id: ****, student_id: ****, name: "Alice", school_id: ****>
Completed in 99ms (View: 7, DB: 33) | 200 OK [https://*********/new_students/search_ajax?option=active&query=s001]

As following in root we have data i want only print root.name in table !!

thanks you

mardi 13 octobre 2020

Is there a way to use a where statement with multiple tables?

I have three tables

Table name: follows
#
#  id         :bigint           not null, primary key
#  following  :bigint
#  requestor  :bigint
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  user_id    :bigint
#
# Indexes
#
#  index_follows_on_user_id  (user_id)
    belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :follows
    )
User
has_many(
    :follows,
    class_name: 'Follow',
    foreign_key: 'user_id',
    inverse_of: :user
  )

Post
belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :posts
    )

The requestor column takes a user.id.

I would only like to show the Posts where the requestor attribute == current_user.id. Am I only able to do this with a join or is there a way to do this with a where statement?

How do I use image_tag in

I'm trying to use the code below to display a user avatar picture. This picture can be accessed by using <%= image_tag(@user.avatar) %>

I'm unsure of how to replace the src= in the code below because previous attempts to replace it ended in failure.

<img class="rounded-circle" width="45" src="https://picsum.photos/50/50" alt="">

Previously I use to used <%= image_tag(@user.avatar, style: 'width:50%') %> to show images, but I prefer the styling of the <img class> more. If anybody can help we out with this on point me into the direction of some documention on this I would greatly appreciate it

lundi 12 octobre 2020

uninitialized constant Faraday::Error::ConnectionFailed in elastic-search

I'm implementing elastic-search in rails by following this tutorial

https://iridakos.com/programming/2017/12/03/elasticsearch-and-rails-tutorial

And add these lines to my User.rb include Elasticsearch::Model include Elasticsearch::Model::Callbacks & also installed these two gems gem 'elasticsearch-model' gem 'elasticsearch-rails' but when I try to execute this command Post.import(force: true) it gives me an error

uninitialized constant Faraday::Error::ConnectionFailed

vendredi 9 octobre 2020

jeudi 8 octobre 2020

AWS SecretsManager password rotation does not work in Rails

We are using AWS SecretsManager (SM) to store a rotating database password for our rails app. However, when SM rotates the password, we get "FATAL: password authentication failed for user".

The password is read in database.yml

password: '<%= AwsSecretService.new.get_db_pwd(ENV['DATABASE_USERNAME']) if Rails.env.production?   %>'

The problem appears to be that ActiveRecord is caching the database credentials from database.yml upon initialization and does not reparse database.yml.

My thought is to somehow trap the authentication failed error and reinitialize ActiveRecord. With the following command:

ActiveRecord::Base.establish_connection(::Rails.application.config.database_configuration[::Rails.env]) 

I'm not sure how to trap the error. Would I need to put an error handler in application_record.rb since all activerecord models inherit from it?

Or would it be better to use an Observer of some sort?

Ideas?

How to destroy model with values

I'm kind of new to rails. I have a model called follows that has to values (requestor and following). I am having trouble creating a button that destroys a select model with two valuesenter image description here



<dt>User ID:</dt>
<dd><%= @user.id %></dd>

<dt>User email:</dt>
<dd><%= @user.email %></dd>

<% if Follow.where(:requestor => current_user.id, :following =>@user.id).present? %>    
    <%= button_to 'Unfollow', follow_url, method: :delete, class: "text-danger", data: { confirm: 'Are you sure?' } %>
<% else %>
    <%= button_to "Follow", {:controller => 'follows', :action => 'create', :requestor => current_user.id, :following => @user.id}, {:method => :post} %>
<% end %>

The Follow button below in the else statement works, but I cannot figure out how to get the destroy button to work. I'm executing these buttons on the User show page instead of on the follow index.enter image description here

def destroy
    @follow.destroy
    respond_to do |format|
      format.html { redirect_to follows_url, notice: 'Follow was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_follow
      @follow = Follow.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def follow_params
      params.permit(:requestor, :following)
    end
    def require_permission
      if Follow.find(params[:id]).user != current_user
        redirect_to goals_url, flash: { error: "You do not have permission to do that."}
      end
    end
end

I keep getting couldn't find Follow with 'id' error. It deletes sometimes, but the majority of the time I get this error.enter image description here

Routes. uses general format

require 'sidekiq/web'

Rails.application.routes.draw do
  resources :follows
  resources :accounts
  resources :goals
  resources :retirements
  get '/users', to: 'users#index'
  get '/user/:id', to: 'users#show', as: 'user'
  resources :calculate_debts
  get '/privacy', to: 'home#privacy'
  get '/terms', to: 'home#terms'
    authenticate :user, lambda { |u| u.admin? } do
      mount Sidekiq::Web => '/sidekiq'
    end


  resources :notifications, only: [:index]
  resources :announcements, only: [:index]
  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
  root to: 'home#index'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end