Friday, January 13, 2017

Rails Edit PDF In Browser and Save To Server | Fixed issues

Rails Edit PDF In Browser and Save To Server | Fixed issues


Rails Edit PDF In Browser and Save To Server

Posted: 13 Jan 2017 07:42 AM PST

I'm working on getting PDF handling to work correctly with our app. Essentially the steps we're doing are:

  1. Render selected PDF form and pre-populate some form fields from server data
  2. User edits remaining PDF form-fields in browser
  3. User edited PDF is posted to the server as a temp file
  4. We use PDFtk to extract the form data and save it to the database

We're stuck on step 3 - I'm unable to post the completed form back to the server using a regular html button. Once it's on the server it'll be easy to manipulate it.

The view looks something like this:

#_form.html.erb  <object data=<%= select_pdf_path(blank_pdf_id: params[:blank_pdf_id], employee_id: params[:employee_id]) %> type="application/pdf" id="filled-pdf"></object>  

I imagine I might have to submit the edited document as a file upload, however, I'm not sure how to grab the edited file and upload it to the back end.


Some of the other solutions I have found require the post buttons to be placed within the PDF form. Unfortunately as we could have thousands of forms this wouldn't be a feasible option. It looks like there are third party options for PHP but nothing I can see for RoR.

Fill up and update an uploaded PDF form online and save it back to the server - Ruby on Rails

Upload file in iFrame

Embed PDF in a website, allow user to modify editable fields in PDF, and save back to the server

Edit pdf embedded in the browser and save the pdf directly to server

saving dates and data in rails with postgres

Posted: 13 Jan 2017 07:40 AM PST

I am using postgres and rails. I have a hotel reservation marketplace app. I am trying to implement unavailable dates for rooms. So to get the unavailable dates from the host i provide a calender for the host to check the dates that is unavailable. So for saving these king of data i add a json field to the table room with unavailable dates which might look like this

"availability":{"days":[{"available":3,"date":"2017-01-19"},{"available":0,"date":"2017-01-20"},{"available":2,"date":"2017-01-22"},{"available":5,"date":"2017-01-23"}]}  

available tells the number of rooms available for that date

Is this ok in the long run? I am bit worried here as this design has the disadvantage of keeping the json record of each and every day and some housekeeping for removing the dates from json when the day is passed. I cant think of another option here. Is this the only option here? Thank you..

regular expression in method to conditionally format record rails 4

Posted: 13 Jan 2017 07:33 AM PST

I'm trying to conditionally set a format of names with a "The" at the beginning. My regular expression works, but I don't know how to make it a conditional statement (basically if this record contains a "the" at the beginning, then "do splitting". As I'm showing a huge table of data, I'd like to keep this efficient.

Class Contact < ActiveRecord::Base    def adjusted_name        if "name LIKE ?", 'The%'        set_name = self.name.split('The ')[1]        self.name = format('%s, The', set_name)      end    end    end  

Trying to create an object that doesn't inherit from ActiveRecord/ApplicationRecord within a Rails controller, but failing

Posted: 13 Jan 2017 07:17 AM PST

I'm trying to create an object within my controller code that doesn't inherit from ActiveRecord. That code is currently an immediate child within my /lib directory. Its name is post_type_specific_data_store.rb:

class PostTypeSpecificDataStore    attr_reader :post_type, :artists, :record_name, :series, :episode_name, :episode_number, :company, :product_name,            :product_version      def initialize(args={})      @post_type = args.fetch(:post_type, nil)      @artists = args.fetch(:artists, nil)      @record_name = args.fetch(:record_name, nil)      @series = args.fetch(:series, nil)      @episode_name = args.fetch(:episode_name, nil)      @episode_number = args.fetch(:episode_number, nil)      @company = args.fetch(:company, nil)      @product_name = args.fetch(:product_name, nil)      @product_version = args.fetch(:product_version, nil)    end  end  

Here's my current controller code located within a file called posts_controller.rb:

class PostsController < ApplicationController    def index      end      def new      if !current_user        redirect_to root_path      end    end      def create      @post = Post.new(post_params)      @post_type_specific_data_store = PostTypeSpecificDataStore.new(post_type_specifc_data_params)      binding.pry    end      private    def post_params      params[:post][:author_id] = current_user.id      params.require(:post).permit(:author_id, :excerpt, :body, :rating, :image_url, :post_type)    end      def post_type_specifc_data_params      params.require(:post_type_specific_data)            .permit(:postType, :artists, :recordName, :series, :episodeName, :episodeNumber, :company, :productName,                    :productVersion)    end  end  

Here's my current React/JSX front-end code:

class NewPost extends React.Component {    constructor(props) {      super(props);      this.state = {        postTypes: ["Music", "Anime", "Products"],        currentPostType: null      };      this.choosePostType = this.choosePostType.bind(this);      this.renderTypeSpecificFields = this.renderTypeSpecificFields.bind(this);      this.renderCommonFields = this.renderCommonFields.bind(this);      this.handleSubmit = this.handleSubmit.bind(this);    }      choosePostType(type) {      this.setState({currentPostType: type})    }      renderTypeSpecificFields() {      let typeSpecificFields;      if (this.state.currentPostType === "Music") {        typeSpecificFields =        <div>          <input type="text" placeholder="Artists (Separate each one by a comma WITHOUT a space)" ref="artists" />          <input type="text" placeholder="Record Name" ref="recordName" />        </div>;      } else if (this.state.currentPostType === "Anime") {        typeSpecificFields =        <div>          <input type="text" placeholder="Series" ref="series" />          <input type="text" placeholder="Episode Name" ref="episodeName" />          <input type="number" min="1" name="Episode Number" ref="episodeNumber" />        </div>;      } else if (this.state.currentPostType === "Products") {        typeSpecificFields =        <div>          <input type="text" placeholder="Company" ref="company" />          <input type="text" placeholder="Product Name" ref="productName" />          <input type="text" placeholder="Product Version" ref="productVersion" />        </div>;      }      return typeSpecificFields;    }      renderCommonFields() {      let commonFields =      <div>        <input type="text" placeholder="Excerpt" ref="excerpt" />        <textarea placeholder="Body" ref="body"></textarea>        <input type="number" min="1" max="7" name="Rating" ref="rating" />        <input type="text" placeholder="Image URL" ref="imageURL" />        <input type="submit" value="Create" />      </div>      return commonFields;    }      handleSubmit(event) {      event.preventDefault();      var post_type_specific_data = {};      post_type_specific_data["postType"] = this.state.currentPostType;      switch (this.state.currentPostType) {        case "Music":          let artists = this.refs.artists.value.split(",");          post_type_specific_data["artists"] = artists;          post_type_specific_data["recordName"] = this.refs.recordName.value;          break;        case "Anime":          post_type_specific_data["series"] = this.refs.series.value;          post_type_specific_data["episodeName"] = this.refs.episodeName.value;          post_type_specific_data["episodeNumber"] = this.refs.episodeNumber.value;          break;        case "Products":          post_type_specific_data["company"] = this.refs.company.value;          post_type_specific_data["productName"] = this.refs.productName.value;          post_type_specific_data["productVersion"] = this.refs.productVersion.value;          break;        default:          break;      }        $.ajax({        url: "/lepostnouveau",        method: "POST",        data: {          post: {            post_type: this.state.currentPostType,            excerpt: this.refs.excerpt.value,            body: this.refs.body.value,            rating: this.refs.rating.value,            image_url: this.refs.imageURL.value          },          post_type_specific_data        }      });    }      render() {      return(        <div>          {            this.state.postTypes.map((postType) => {              let choosePostWithType = this.choosePostType.bind(this, postType);              return(                <PostTypeChooser key={postType}                                 type={postType}                                 choose={choosePostWithType} />              )            })          }          <form onSubmit={this.handleSubmit}>            {this.renderTypeSpecificFields()}            {this.renderCommonFields()}          </form>        </div>      )    }  }  

And lastly, here's the error I get:

NameError: uninitialized constant PostsController::PostTypeSpecificDataStore  

Thanks ahead of time!

rails assign variable value to param

Posted: 13 Jan 2017 06:50 AM PST

I'm trying to assign the param 'starts_at' value to the @schedule_item variable, using the following code:

    @schedule_item = ScheduleItem.new      @schedule_item.schedule = @schedule        if params[:starts_at].present?        @schedule_item.starts_at = params[:starts_at]      end  

However, when I place a binding.pry after the if statement, I see @schedule_item.starts_at is still nil. I also know that 'params[:starts_at]' returns => "01/17/2017 12:00 AM". Any thoughts?

How to start work with Gmail API in Rails 4

Posted: 13 Jan 2017 07:41 AM PST

I would like to add Gmail to my Rails 4 app. So far I have set up everything so user can log in with Google account. I followed this guide.

Now when user tries to log in my Rails 4 app he receives such onscreen :

enter image description here After "Allow" user is redirected back to my Rails 4 app.

Initializers/omioauth.rb

OmniAuth.config.logger = Rails.logger    Rails.application.config.middleware.use OmniAuth::Builder do    provider :google_oauth2, Rails.application.secrets.client_id, Rails.application.secrets.client_secret, {scope: ['email',      'https://www.googleapis.com/auth/gmail.modify'],      access_type: 'offline', client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}  end  

All authorization data from Google is located in secrets.yml.

Installed gems:

gem "omniauth-google-oauth2", "~> 0.2.1"  gem "google-api-client"  

Question: What are the next steps to implement Gmail API in Rails project? How to retrieve my Gmail inbox content.. So far I haven't found complete and self-explaining guide to do so.

I found Gmail gem, but the guide is very incomplete for Rails begginers.

For example, I installed this gem and then tried to require 'gmail' in rails c . Then I received error uninitialized constance 'gmail'.

Note: I don't need full solution to my problem,but just a push to start going and I could understand idea.

Thanks in advance.

Dynamic menu based on current params in Rails

Posted: 13 Jan 2017 07:23 AM PST

I'm trying to build a Rails helper that will create a nested dropdown menu containing links where the top most is either 'All' or the current param and the dropdown contains the other options excluding the current param if there is one.

So for example if I have no post_type param I would see:

<ul>      <li><a href="">All</a>          <ul>              <li><a href="">Discussions</a></li>              <li><a href="">Snaps</a></li>              <li><a href="">Code</a></li>              <li><a href="">Links</a></li>          </ul>      </li>  </ul>  

But if I had a post_type param of 'discussion' then I would see:

<ul>      <li><a href="">Discussions</a>          <ul>              <li><a href="">All</a></li>              <li><a href="">Snaps</a></li>              <li><a href="">Code</a></li>              <li><a href="">Links</a></li>          </ul>      </li>  </ul>  

In my view I have:

<ul class="filter-menu">    <li>      <%= current_post_type(params) %>      <ul class="filter-menu__drop-down">        <%= list_post_types(params) %>      </ul>    </li>  </ul>  

And in my Helper I have the following:

module PostsHelper      def post_types      @post_types = {          :all => {              :text => 'All post types',              :icon => 'icon-file-text2',              :post_type => nil}      }, {          :discussions => {              :text => 'Discussions',              :icon => 'icon-bubbles2',              :post_type => 'discussions'}      }, {          :snaps => {              :text => 'Snaps',              :icon => 'icon-images',              :post_type => 'snaps'}      }, {          :code => {              :text => 'Code',              :icon => 'icon-embed2',              :post_type => 'code'}      }, {          :links => {              :text => 'Links',              :icon => 'icon-link',              :post_type => 'links'}      }    end      def post_type_path(post_type)      posts_path(:filter => params[:filter], :time => params[:time], :post_type => post_type)    end      def current_post_type(params)      if params[:post_type].present? # todo: check matches above        post_type = params[:post_type].downcase        link_to raw('<i class="' + post_types[post_type][:icon] + '"></i> ' + post_types[post_type][:text] + ' <span class="chevron">&#9662;</span>'), post_type_path(post_types[post_type][:post_type])      else        link_to raw('<i class="' + post_types[:all][:icon] + '"></i> ' + post_types[:all][:text] + ' <span class="chevron">&#9662;</span>'), post_type_path(post_types[:all][:post_type])      end    end      def list_post_types(params)      post_types.each do |post_type| # todo: exclude current post_type        link_to raw('<i class="' + post_types[post_type][:icon] + '"></i> ' + post_types[post_type][:text]), post_type_path(post_types[post_type][:post_type])      end    end    end  

How do I loop through the hash though? I get an error no implicit conversion of Symbol into Integer

Also how could I check that the params[:post_type] exists in the hash for the current_post_type helper and exclude it from the list_post_types helper.

How to build json params in Httparty

Posted: 13 Jan 2017 06:39 AM PST

I have to send a post request in httparty and get response my json params are

    {    "webhook": {      "topic": "shop/update",      "address": "http://2350d6c0.ngrok.io/shopify_stores/update_shop_info",      "format": "json"    }  }  

And i am using httparty params as

begin            response = HTTParty.post("#{url}",            {               :body => [                  {                      "webhook" => {                          "topic" => "shop\/update",                          "address" => "http:\/\/15ec3a12.ngrok.io\/shopify_stores\/update_shop_info", #place your url here                          "format" => "json"                      }                  }                          ].to_json,              :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json'}            })            byebug          rescue HTTParty::Error        end  

but it repsonse is

Required parameter missing or invalid

Ruby on Rails - Route not found [duplicate]

Posted: 13 Jan 2017 06:22 AM PST

This question already has an answer here:

I have a CommunitiesSearchController with a search method.

I defined its route like this:

namespace :api, defaults: { format: 'json' } do      namespace :v1 do                  resources :communities        get 'community/search/coordinates/:latitude/:longitude', to: 'communities_search#search'      end    end  

But when I try to access it:

ActionController::RoutingError (No route matches [GET] "/api/v1/community/search  /coordinates/49.2864807/-123.142214"):  

I'm using rails 5.

Which is the WP on Rails wp_connector's valid API Key

Posted: 13 Jan 2017 06:13 AM PST

I was building a simple blog system where content management is done on Wordpress and data from the Wordpress database displayed using a Rails app.

I have followed the https://github.com/wponrails/wp-connector manual/explaination step by step but i keep on getting an error on rails development.log saying: Filter chain halted as :require_valid_api_key rendered or redirected Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)

The wp_connector API key that am using is H3O5P6P1I5N8G8E4R. Does anyone knows the valid API key that I should be using and/or how to go about this problem.

Kind Regards.

Rails API .permit() is not working as expected

Posted: 13 Jan 2017 07:09 AM PST

I have a controller and utilizing the require and permit methods to control what can be submitted to the API. Not sure when or what I changed but now the API is allowing all params to be excepted. I have looked through source control and don't see anything that really jumps out at me why it would now allow all params.

Controller: Project Controller

Model: Project Model

The API controller is now allowing below, even though ':blah' is not a white listed param.

{"project_id":2,"location_id": 2,"blah":"blah"}  

Any help would be great! Is there some global setting or anything? If you need more info. let me know

rails self-referential collections based on model not providing full object

Posted: 13 Jan 2017 06:29 AM PST

I'm working with a join table (Neighborhoods) that points to the Country table in order to establish which countries are neighbors.

For some reason one relationship (centers) returns the collection as expected, which allows me to reference both the id AND the name. Why doesn't the relationship for neighborhoods return the full row from country table?

DB Schema

Table: Neighborhoods t.integer "target_id" t.integer "neighbor_id"

Table: Countries t.integer "country_id"

Models

Neighborhood belongs_to :neighbor, class_name: "Country" belongs_to :target, class_name: "Country" validates :neighbor_id, presence: true validates :target_id, presence: true

Country has_many :neighborhoods, class_name: "Neighborhood", foreign_key: "neighbor_id", dependent: :destroy has_many :centers, through: :neighborhoods, source: :target

Example:

> c = Country.first // setup my target id to be called by rails   > c.centers // using target id call the neighbor    [["neighbor_id", 2]]   => #<ActiveRecord::Associations::CollectionProxy [#<Country id: 6, name: "new C", description: nil, size: nil, created_at: "2017-01-12 19:31:50", updated_at: "2017-01-12 19:31:50">,  

This collection is what I want. The other relationship when called in the same way returns a collection with just two id's in it AND without the name in it ... why?

Example:

> c.neighborhoods     [["neighbor_id", 2]]   => #<ActiveRecord::Associations::CollectionProxy [#<Country id: 6, name: "new C", description: nil, size: nil, created_at: "2017-01-12 19:31:50", updated_at: "2017-01-12 19:31:50">, ...  

Ruby on Rails - Dropdown list influenced by another

Posted: 13 Jan 2017 06:20 AM PST

I have a project, and related to this project i have course and course unit.

When I created a project I wanted to choose a course and depending on the course I chose, I wanted to choose a course unit.

I have this 3 models

class CourseUnit < ApplicationRecord                                            belongs_to :course      has_many :projects, dependent: :destroy  end    class Course < ApplicationRecord      has_many :course_units, dependent: :destroy      has_many :projects, through: :course_units  end    class Project < ApplicationRecord         belongs_to :course_unit  end  

Anyone have any idea how I can do it?

How to convert gif to webm on upload using paperclip and/or paperclip-av-transcoder?

Posted: 13 Jan 2017 05:31 AM PST

All docs describe how to create thumbnails out of videos. But what if I don't want to store the original large gif files, but convert them to webm videos which are of a much smaller size?

class MediaAttachment < ApplicationRecord    IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze    VIDEO_MIME_TYPES = ['video/webm', 'video/mp4'].freeze      has_attached_file :file,                      styles: -> (f) { file_styles f },                      processors: -> (f) { f.video? ? [:transcoder] : [:thumbnail] },                      convert_options: { all: '-quality 90 -strip' }    validates_attachment_content_type :file, content_type: IMAGE_MIME_TYPES + VIDEO_MIME_TYPES    validates_attachment_size :file, less_than: 4.megabytes      def image?      IMAGE_MIME_TYPES.include? file_content_type    end      def video?      VIDEO_MIME_TYPES.include? file_content_type    end      class << self      private        def file_styles(f)        if f.instance.image?          {            original: '1280x1280>',            small: '400x400>',          }        else          {            small: {              convert_options: {                output: {                  vf: 'scale=\'min(400\, iw):min(400\, ih)\':force_original_aspect_ratio=decrease',                },              },              format: 'png',              time: 1,            },          }        end      end    end  end  

The above code allows users to upload images or webm/mp4 videos, and creates a thumbnail out of the videos. How do I make it so gifs are converted and stored as webms (and then a thumbnail is generated just like for other videos)?

How can I push a small change to heroku from my rails app without it taking 4 minutes?

Posted: 13 Jan 2017 04:52 AM PST

Every time I push to heroku, it is running bundle install and it takes me about 4 minutes. This is a small app that is not live yet. What if I only want to push a single change where I add one character to a view file? Is there anyway that I can tell heroku, here change this file and do it quickly without having to wait 4 minutes to run bundle install and everything else it does?

Ruby on Rails: Adding jQueryUI and Bootstrap icons on production environment

Posted: 13 Jan 2017 04:37 AM PST

I have problem with showing icons on production environment. I located files jQueryUI and Bootstrap in /vendor/ directory, then i add config.assets.paths in assets.rb:

Rails.application.config.assets.paths << Rails.root.join("vendor/bootstrap-3.3.7-dist")
Rails.application.config.assets.paths << Rails.root.join("vendor/jquery-ui-1.12.1")

I also added 'require' statements in app/assets/stylesheets/application.css and app/assets/javascripts/application.js. After that i try:

RAILS_ENV=production bundle exec rake assets:precompile

and restart apache. Bootstrap and jQueryUI works fine but i can't add icons (or glyphicons from Bootstrap). When i change environment to development icons works fine. The problem is only on production environment. I have tried add png files with icons and fonts files with glyphicons to /vendor/assets/images/ and app/assets/images/ and then change url addresses in css files to assests/images/file_name.png but it doesn't work. Could it be some issue with configuration config/environments/production.rb or something like that? It is strange that everything works fine on development, but production not.

Elasticsearch-rails query not understood

Posted: 13 Jan 2017 04:19 AM PST

I am using elasticsearch-rails and elasticsearch-model gem for searching words in my rails app.

Here is my model article.rb where I want to search to take place:

require 'elasticsearch/model'        class Article < ActiveRecord::Base        include Elasticsearch::Model        include Elasticsearch::Model::Callbacks          settings index: { number_of_shards: 1 } do          mappings dynamic: 'false' do            indexes :title, analyzer: 'english', index_options: 'offsets'            indexes :text, analyzer: 'english'          end        end          def self.search(query)          logger.info "LocationController.add_locations called with params: #{query}"          __elasticsearch__.search(            {              query: {                multi_match: {                  query: query,                  fields: ['title^10', 'text']                }              },              highlight: {                pre_tags: ['<em>'],                post_tags: ['</em>'],                fields: {                  title: {},                  text: {}                }              }            }          )        end      end        # Delete the previous articles index in Elasticsearch      Article.__elasticsearch__.client.indices.delete index: Article.index_name rescue nil        # Create the new index with the new mapping      Article.__elasticsearch__.client.indices.create \        index: Article.index_name,        body: { settings: Article.settings.to_hash, mappings: Article.mappings.to_hash }        # Index all article records from the DB to Elasticsearch      Article.import        #Article.import force: true  

I did it referring some content from google. but I am not properly understand how it works, mainly following lines:

settings index: { number_of_shards: 1 } do      mappings dynamic: 'false' do        indexes :title, analyzer: 'english', index_options: 'offsets'        indexes :text, analyzer: 'english'      end  

and

__elasticsearch__.search(        {          query: {            multi_match: {              query: query,              fields: ['title^10', 'text']            }          },          highlight: {            pre_tags: ['<em>'],            post_tags: ['</em>'],            fields: {              title: {},              text: {}            }          }        }      )  

Mongoid not showing the right translation when rendering

Posted: 13 Jan 2017 04:16 AM PST

I'm using the Mongoid localize field to take advantage of automatic translation. This is easily done:

Class Post    field :title, localize: true  end  

I also have the translations (English and Turkish):

> Post.first.title_translations  {"en"=>"Cool kid drinking den with a strong snack menu", "tr"=>"Sağlam atıştırmalık menüsü olan cool çocukların barı"}  

Then, in my controller, I get the locale variable from the URL parameters, set it temporarily, get the results and show them as JSON:

class PostsController < ActionController::Base      around_filter :set_locale      def index      posts = Post.all      # binding.pry        respond_to do |format|        format.json { render json: posts, content_type: 'application/json' }      end    end    private      def set_locale      I18n.with_locale(request_locale || I18n.default_locale) do        yield      end    end      def request_locale      params[:locale].blank? ? nil : params[:locale].to_sym    end    end  

The problem is that no matter how I change the locale value (en or tr), the JSON result is always the same in the browser.

Uncommenting binding.pry in the controller helps to validate the logic. If I have /?locale=en in my URL, and I type:

> posts.first.title  "Cool kid drinking den with a strong snack menu"  

And if I change /?locale=tr, I get:

> posts.first.title  "Sağlam atıştırmalık menüsü olan cool çocukların barı"  

It seems to work with the console, but not on my browser?

Do you have any idea on that! I must use Mongoid 4.0.2, and the Rails application I'm working on is 4.2.5

Thanks

How to add methods to classes in a Rails project from a gem/engine?

Posted: 13 Jan 2017 04:25 AM PST

I would like to make a gem that adds a helper method into ApplicationController. Then all I would have to do would be to use the gem in the Gemfile and the helper method would automagically be avalable in every main_app controller and view.

So for I have a Rails engine with such a structure:

app/    controllers/      application_controller.rb    class ::ApplicationController < ActionController::Base    # NB, this extends the main app's application controller      helper_method :is_available_in_main_app?      protected      def is_available_in_main_app?                  return true      end    end  

Unfortunately, the method does not seem to get picked up since I am getting undefined method 'is_available_in_main_app?' for <ApplicationController:0x007fb04d446d80>

Articles like Reopening Ruby Classes lead me to believe that this should work.
It some Rails magic preventing it?

Ruby on Rails - Render new on show

Posted: 13 Jan 2017 04:12 AM PST

I have nested resources and I'm trying to show the new layout for the nested resource on the show of the parent.

resources :discussions do      resources :comments  end  

discussions\show.html.erb

<%= @discussion.title %>  <%= ... render the discussion %>  <%= ... render the existing comments %>  <% render 'comments/new' %>    <--- trying something like this  

comments/new throws an error because it's missing the partial.
comments/form works to get past that, but throws an error saying my @comment is nil.

comments/_form.html.erb

undefined method discussion for nil:NilClass

<%= bootstrap_form_for([ @comment.discussion, @comment] ) do |f| %>

Do I have to change something in the controller, or am I going about this incorrectly?

Thanks for your help!

How to upload base64 image to s3 from rails controller?

Posted: 13 Jan 2017 04:58 AM PST

I am making an ajax reject to my controller with some data and base64 image and now I want to upload this image to s3 and replace base64 with the image url. I am following this https://sebastiandobrincu.com/blog/how-to-upload-images-to-rails-api-using-s3

 def split_base64(uri_str)            if uri_str.match(%r{^data:(.*?);(.*?),(.*)$})              uri = Hash.new              uri[:type] = $1 # "image/gif"              uri[:encoder] = $2 # "base64"              uri[:data] = $3 # data string              uri[:extension] = $1.split('/')[1] # "gif"              return uri            else              return nil            end  end    def convert_data_uri_to_upload(image_url)                          image_data = split_base64(image_url)              image_data_string = image_data[:data]              image_data_binary = Base64.decode64(image_data_string)                temp_img_file = Tempfile.new("")              temp_img_file.binmode              temp_img_file << image_data_binary              temp_img_file.rewind                img_params = {:filename => "image.#{image_data[:extension]}", :type => image_data[:type], :tempfile => temp_img_file}              uploaded_file = ActionDispatch::Http::UploadedFile.new(img_params)            end      return uploaded_file      end  

Now from my controller I am passing convert_data_uri_to_upload(base64_image)

Now I don't know where to write the AWS credentials. According to the url I have to write the credentials in Fog.rb file but I don't have any such file. I have created one ImageUploader inside uploader folder which extends CarrierWave and wrote the configurations but it is also not working.

Handling File Uploads from Mobile Application to a Rails End Point using Shrine

Posted: 13 Jan 2017 03:28 AM PST

So I have a Rails Application which uses Shrine as its File Uploader. The same app has a mobile client which can click and send pictures. Currently, the mobile is clicking pictures and sending them to AWS S3 and then returning the S3 URL back to Rails to associate with the object. At this point, once Shrine received this S3 URL I save it to object.upload_remote_url. Following which Shrine again uploads it to S3 thus making 2 requests to S3 for every image that comes via the JSON API.

  1. What I would like to know is, what is the best practise to handle file uploads from Mobile to Web Server to S3? What are the best techniques developers use?
  2. How to send files from mobile as JSON. I know images can be converted to Base64 String and then sent but what other options are available?
  3. Shrine Gem with S3 plugin has a copy option, which correct me if I am wrong, checkes for the image in the source bucket and copies it over to the destination bucket. http://shrinerb.com/rdoc/classes/Shrine/Storage/S3.html#class-Shrine::Storage::S3-label-Upload+options

Below is my Shrine Configs

require "shrine/storage/s3"    s3_options = {    access_key_id:     Rails.application.secrets.aws_access_key_id,    secret_access_key: Rails.application.secrets.aws_secret_access_key,    region:            Rails.application.secrets.aws_region,    bucket:            Rails.application.secrets.aws_bucket,  }    copy_from = {      copy_source: "#{Rails.application.secrets.aws_bucket}/mobile"  }    Shrine.storages = {    cache: Shrine::Storage::S3.new(prefix: "cache", upload_options: {acl: "public-read"}, **copy_from, **s3_options),    store: Shrine::Storage::S3.new(prefix: "store", upload_options: {acl: "public-read"}, **copy_from, **s3_options)  }    Shrine.plugin :activerecord  Shrine.plugin :direct_upload  Shrine.plugin :restore_cached_data  Shrine.plugin :upload_options  

I am trying to work with option #3 but I'm stuck trying to getting it to work. Can anyone help me understand it?

Matching algorithm in Ruby on Rails

Posted: 13 Jan 2017 03:22 AM PST

In my Rails project I need to match Profiles to a certain set of criteria. My current setup is that each profile has a set of Evaluations, where the latest evaluation is the active one. Each Evaluation consists of a set of Properties which may have a value from 0 to 4. I would like to create a custom "filter-evaluation" (namespace is ProfessionProfile in my code) and find all Profiles who's latest evaluation is either better or equal (higher or equal values for each Property) than the filter.

My current solution works but makes a huge amount of requests to the server, thus taking a lot of time, I would like to instead do this in a single request. FYI PostgreSQL is used.

Current solution:

filters_controller.rb:

def filter_by_profession(profiles)      hits = []      profession = ProfessionProfile.find(params[:profession])      Profile.find_each do |p|          if p.has_better_values(profession)              hits << p          end       end      profiles = profiles.where(id: hits.map(&:id))  end  

profile.rb:

def has_better_values(profession_profile)      latest_evaluation = property_evaluations.order(:created_at).first      if latest_evaluation.present?          latest_evaluation.property_values.each do |value|              profession_value = profession_profile.property_values.where(property_id: value.property_id)              return false if profession_value.present? && value.value < profession_value.take!.value          end          return true      else          return false      end  end  

Instead of doing this I have tried the following solution but it always returns an empty set, even when I should have a match.

def filter_by_profession(profiles)      profession_profile = ProfessionProfile.find(params[:profession])      profiles = profiles.joins(:property_values)      profession_profile.property_values.find_each do |property_value|        profiles = profiles                        .where("property_values.property_id = ?", property_value.property_id)                        .where("property_values.value >= ? ", property_value.value)      end      profiles  end  

Any tips or help would be appreciated!

I have seen a similar question here but I failed to adapt it to my situation.

Rails using Views instead of Tables

Posted: 13 Jan 2017 03:22 AM PST

I need to create a Rails app that will show/utilize our current CRM system data. The thing is - I could just take Rails and use current DB as backend, but the table names and column names are the exact opposite Rails use.

Table names:

+-------------+----------------+--------------+  | Resource    | Expected table | Actual table |  +-------------+----------------+--------------+  | Invoice     | invoices       | Invoice      |  | InvoiceItem | invoice_items  | InvItem      |  +-------------+----------------+--------------+  

Column names:

+-------------+-----------------+---------------+  | Property    | Expected column | Actual column |  +-------------+-----------------+---------------+  | ID          | id              | IniId         |  | Invoice ID  | invoice_id      | IniInvId      |  +-------------+-----------------+---------------+  

I figured I could use Views to:

  • Normalize all table names
  • Normalize all column names
  • Make it possible to not use column aliases
  • Make it possible to use scaffolding

But there's a big but:

  • Doing it on a database level, Rails will probably not be able to build SQL properly
  • App will probably be read-only, unless I don't use Views and create a different DB instead and sync them eventually

Those disadvantages are probably even worse when you compare it to just plain aliasing.

And so I ask - is Rails able to somehow transparently know the id column is in fact id, but is InvId in the database and vice versa? I'm talking about complete abstraction - simple aliases just don't cut it when using joins etc. as you still need to use the actual DB name.

I need erb to loop and render out the children of several objects and the children of the children

Posted: 13 Jan 2017 06:25 AM PST

Lets say I have a collection of objects, and each one may or may not have children, and that child collection may or may not have children for an unknown number of generations.

How do I get erb to render all the way to the last child of each tree?

Humans

[  {name: bill, id: 1, human_id: nil},  {name: bob, id: 2, human_id: 1},  {name: john, id: 3, human_id: 2},  {name: marie, id: 4, human_id: 2},  {name: anne, id: 5, human_id: nil},  {name: jake, id: 6, human_id: 5},  ]  

As you can see there are two records that begin the tree (1 and 5), because they do not belong to anyone.

I need to render

bill      bob          john          marie  anne      jake  

without knowing how many relationship layers there are

Excon::Errors::Timeout: connect timeout reached

Posted: 13 Jan 2017 04:02 AM PST

I am using sidekiq to send mails through Mandrill Apis. It was working all fine. But from past few days I am receiving timeout errors in sidekiq while job try to deliver mail randomly.

Excon::Errors::Timeout: connect timeout reached

I am unable to find the actual cause of this error. I am using

  • ruby '2.1.1'
  • sidekiq '3.5.0'
  • mandrill_mailer '1.1.0'
  • mandrill-api '1.0.53'

Here is the complete error

2017-01-11T17:34:06.068Z 3690 TID-otkzvfo0c WARN: Excon::Errors::Timeout: connect timeout reached  2017-01-11T17:34:06.068Z 3690 TID-otkzvfo0c WARN: /home/shared/bundle/ruby/2.1.0/gems/excon-0.45.4/lib/excon/socket.rb:139:in `rescue in block in connect'  /home/shared/bundle/ruby/2.1.0/gems/mandrill-api-1.0.53/lib/mandrill.rb:35:in `call'  /home/shared/bundle/ruby/2.1.0/gems/mandrill-api-1.0.53/lib/mandrill/api.rb:921:in `send_template'  /home/shared/bundle/ruby/2.1.0/gems/mandrill_mailer-1.1.0/lib/mandrill_mailer/template_mailer.rb:121:in `deliver'  /home/app/mailers/sub_request_mailer.rb:651:in `sub_request_approved_location'  /home/shared/bundle/ruby/2.1.0/gems/mandrill_mailer-1.1.0/lib/mandrill_mailer/core_mailer.rb:290:in `call'  /home/shared/bundle/ruby/2.1.0/gems/mandrill_mailer-1.1.0/lib/mandrill_mailer/core_mailer.rb:290:in `method_missing'  

Using acts_as_paranoid with DelayedJob?

Posted: 13 Jan 2017 02:55 AM PST

Can someone tell me precisely how to integrate acts_as_paranoid with DelayedJob? I've tried creating a class Delayed::Backend::ActiveRecord::Job and adding acts_as_paranoid to it but even if I use an initializer and require the new class, acts_as_paranoid doesn't seem to do anything.

I'm not getting any errors so paranoia seems to be installed correctly and the job is cleanly deleted when it completes successfully - which is of course what I'm trying to prevent.

Happy to try any debugging suggestions if nobody reads this and immediately knows how I've screwed up.

Sidekiq - delay until 3 days before a variable date - is it possible?

Posted: 13 Jan 2017 03:07 AM PST

I'm using Ruby on Rails and currently using Sidekiq to delay the sending of an email to a user for 3 days (after a create action) as such:

QuickcontactMailer.delay_until(3.days.from_now).reminder(@quickcontact)  

I'm trying to find out if it's possible to use a variable date instead of "from_now", something like this:

QuickcontactMailer.delay_until(3.days.from(@quickcontact.date_required).reminder(@quickcontact)  

I can't find any information about it, maybe I'm asking to do a bit too much here. Any help would be great thanks.

HTML video background with Ruby on Rails

Posted: 13 Jan 2017 06:52 AM PST

I am a beginner on Ruby on rails and I am building an application in which have a Video Header Background. The application works fine locally, but once I tried to upload it to Heroku the video-background does not play. The app is still in development.

I get in my Web-browser console the following messages:

HTTP load failed with status 404. Load of media resource https://serene-fortress-58125.herokuapp.com/assets/Islands.mp4 failed.   All candidate resources failed to load. Media load paused.   

I am thinking that I should host the video in some sort of hosting service to make it available to the Heroku app, but I need to figure out how that could work with my current html code and which hosting service to use. I tried with tinypic to host the video, but the video was played as x-shockwave-flash and not compatible with my current web design.

I was thinking of using the tubular jquery plug in as adviced in the following post and using Youtube as host:

Fullscreen video background - <video> vs YouTube/Vimeo-<iframe>?

I would maybe need a couple of advices on how to use jquery with Ruby on Rails 5.0.1 and what would be the best practice to make this work out. Any advice would be really helpful.

Thanks a lot

Fabrizio

This is my app on Heroku: https://serene-fortress-58125.herokuapp.com/

This is my git: https://github.com/fabriziobertoglio1987/portfolio

This are links to similar unanswered questions on Stackoverflow:

adding an animated background to a ruby on rails app

Ruby on Rails- HTML5 Video as background for landing page not loading on heroku

Elasticsearch-rails How to increase accuracy in result as expected?

Posted: 13 Jan 2017 02:50 AM PST

I am using elasticsearch-rails and elasticsearch-model gem for searching words in my rails app.

Here is my model article.rb where I want to search to take place:

require 'elasticsearch/model'    class Article < ActiveRecord::Base    include Elasticsearch::Model    include Elasticsearch::Model::Callbacks      settings index: { number_of_shards: 1 } do      mappings dynamic: 'false' do        indexes :title, analyzer: 'english', index_options: 'offsets'        indexes :text, analyzer: 'english'      end    end      def self.search(query)      __elasticsearch__.search(        {          query: {            multi_match: {              query: query,              fields: ['title^10', 'text']            }          },          highlight: {            pre_tags: ['<em>'],            post_tags: ['</em>'],            fields: {              title: {},              text: {}            }          }        }      )    end  end    # Delete the previous articles index in Elasticsearch  Article.__elasticsearch__.client.indices.delete index: Article.index_name rescue nil    # Create the new index with the new mapping  Article.__elasticsearch__.client.indices.create \    index: Article.index_name,    body: { settings: Article.settings.to_hash, mappings: Article.mappings.to_hash }    # Index all article records from the DB to Elasticsearch  Article.import    #Article.import force: true  

Here is my search.html.erb:

<h1>Articles Search</h1>    <%= form_for search_path, method: :get do |f| %>    <p>      <%= f.label "Search for" %>      <%= text_field_tag :q, params[:q] %>      <%= submit_tag "Go", name: nil %>    </p>  <% end %>    <ul>    <% @articles.each do |article| %>      <li>        <h3>          <%= link_to article.try(:highlight).try(:title) ? article.highlight.title[0].html_safe : article.title,            controller: "articles",            action: "show",            id: article._id%>        </h3>        <% if article.try(:highlight).try(:text) %>          <% article.highlight.text.each do |snippet| %>            <p><%= snippet.html_safe %>...</p>          <% end %>        <% end %>      </li>    <% end %>  </ul>  

Here is my routes.rb:

Rails.application.routes.draw do    resources :articles    get 'search', to: 'search#search'  end  

Here is my search_controller.rb:

class SearchController < ApplicationController    def search      if params[:q].nil?        @articles = []      else        @articles = Article.search params[:q]      end    end  end  

Now, I am getting results only matching words. My questions are: How I can do composite matching? I am not understood how this function works- and how to change queries??

 def self.search(query)              __elasticsearch__.search(                {                  query: {                    multi_match: {                      query: query,                      fields: ['title^10', 'text']                    }                  },                  highlight: {                    pre_tags: ['<em>'],                    post_tags: ['</em>'],                    fields: {                      title: {},                      text: {}                    }                  }                }              )            end          end  

also How can I increase accuracy like composite match, spell check, partial matching? Thank You.

No comments:

Post a Comment