vendredi 3 juillet 2015

Base64 Encode Image and Save it later to a file

I have an application where an admin can upload an image. I save the image in a file and also base64 encode (using Base64.strict_encode method of ruby) & save in my DB. This is so that when later someone deleted the physical file from the HDD/Server, I can still generate it back by base64 decoding it (Base64.decode method) and save in a file.

But the encoding and decoding didn't go well as the image get damaged and I'm unable to view it after save.

I checked the output of the Base64.strict_encode against the result when I used http://ift.tt/123NYKL to encode the file, they were different.

Can anyone help me with this? What am I doing wrong? What am I not doing?

ENCODING THE IMAGE DURING UPLOAD:

  imageLoc = image.image.to_s
  logger.info '>>>>>>' + (Base64.strict_encode64(open(imageLoc).read)).to_s
  image_data = Base64.strict_encode64(File.open(imageLoc, 'rb').read)
  CategoryImage.update_image_data(image.id,image_data)

DECODING WHEN IMAGE FILE IS LOST:

File.open(File.join(APP_CONFIG['image_storage_location'], image[:image]), 'wb') { |f|
    content = image[:image_data]
    content.gsub!('\\r', "\r")
    content.gsub!('\\n', "\n")
    f.write(Base64.decode64(content))
    f.close
  }

ENCODED IMAGE FROM THE SITE (base64-image.de): http://ift.tt/1IVh2mm

ENCODED IMAGE FROM MY CODE: http://ift.tt/1C6cjRx

jeudi 2 juillet 2015

Rails App linux-build on Windows

Am a total newbie to Rails World. I have developed some apps just for the sake of learning. Now am about to make a huge app for some purpose. As i have installed Linux-Mint and after so much struggle i was able to install Rails without errors. Now issue is that, I have started building Rails app in linux-Mint environment but my client for whom building it isn't aware of any Linux based OS. and Know only about windows. He also don't want to put app online but want to use it on Localhost. so is it possible that i Make the whole app on Linux-Mint and he will be able to use it on Windows localhost , as there are many limitations of GEMS on windows. Have searched a lot about it but didn't find anything except Notes on limitation of Rails on windows so any help will be great.

Establish external database connection in production on Heroku

I am trying to establish a connection to a secondary, external database on Heroku (this is a PostgreSQL db running on AWS). I am trying to find the easiest and/or best way to do this.

I have tried using a Capistrano task to copy the database.yml file during deployment to Heroku:

after "deploy:update_code","deploy:config_symlink"

namespace :deploy do

  task :config_symlink do
    run "cp #{shared_path}/shared/config/database.yml #{release_path}/config/database.yml"
  end
end

I have tried establishing the connection via Heroku config vars:

class Pgdb < ActiveRecord::Base.establish_connection(
    :adapter => ENV['PG_ADAPTER'],
    :database => ENV['PG_DB'],
    :username => ENV['PG_USER'],
    :password => ENV['PG_PW'],
    :host => ENV['PG_HOST']
  )

  self.abstract_class = true
  self.table_name = 'test'

  def self.getCardInfo(card_name)
    get = connection.query("SELECT * FROM test)
    get
  end
end

I can't find any documentation that makes sense or tells me exactly how to do this. I do not know if I'm close or way off in the attempts above. I'm looking for any solution that fixes the above attempts or any other solution to this problem.

Getting 304 Error in response of jquery request

Scenario:

  1. User visit the page

  2. Jquery started to make ajax request to backend code

  3. Navigate to page (not refreshing) I can see the request still going to server from client. It supposed to be stopped now.
  4. When user return to same page again, Request should started to hit but it's throwing 304 error. Jquery supposed to hit the request again.

User click on following button code

index.html.erb

<td colspan="3"><%= link_to 'Show state', simulation, :class => 'btn btn-primary' %></td>

will navigate to

show.html.erb

Here I have written the jquery code to making Ajax request

<script>
$(function() {setInterval(function(){ $.get("/posts/<%= @post.id %>"); }, 5000);
});

Dom needed to be changes after every `Ajax` response in same views (show.html.erb)

<span id="post-data">
  <table class = 'table table-hover'>
     .....
  </table>
</span>

js file for rendering the views

in show.js.erb

$("#post-data").html(" <table> ... </table>") 

How can I fix these errors. Any help would be appreciable, I am not a core javascript guy.

Get key from hash if value in it zero

I have 3 array region ,min,max.If min and corresponding max is both 0 then I want to get the corresponding region into an array.

region=["A","B","C","D","E","F","G"]
min= ["0","0","0","200","400","0","0"]
max= ["0","0","0","1000","1000","0","0"]

Expected output :

output=["A","B","C","F","G"]

In the above..ABCFG has corresponding min and max both 0..so I want those region valuse..i.e regions which has both min and max 0

I tried below but no able to proceed furthur

Hash[region.zip([min.map(&:to_i),max.map(&:to_i)].transpose)]

//output
{"A"=>[0, 0], "B"=>[0, 0], "C"=>[0, 0], "D"=>[200, 1000], "E"=>[400, 1000], "F"=>[0, 0], "H"=>[0, 0]}

How to run minitest for controller methods?

post_controller file

class PostsController < ActionController::Base
before_action :authenticate_user!

def index
 @post = current_user.posts.paginate(page: params[:page], per_page: 5)
 respond_to do |format|
   format.html
   format.json { render json: @post }
 end
end

def new
 @post = Post.new
end

def create
 @post = current_user.posts.build(post_param)
 if @post.save
   redirect_to action: 'index'
 else
   render 'new'
 end

post_controller_test

require 'test_helper'

class PostsControllerTest < ActionController::TestCase
include Devise::TestHelpers

def setup
 @user  = users(:Bob)
 @post = Post.new
end  #passed

test 'logged in should get show' do
 sign_in @user
 get :index
 assert_response :success
end  #passed

test 'not authenticated should get redirect' do
 get :index
 assert_response :redirect
end   #passed  

test 'should get index' do
 get :index
 assert_response :success
 assert_not_nil assigns(:posts)
end   #failing

test "should destroy post" do
 assert_difference('Post.count', -1) do
 delete :destroy, id: @post
end

assert_redirected_to posts_path
end   #failing
...  

devise is setup and working fine but why I am getting 302 error in last two cases. Is it because I am not passing @user parameters to it? I did but it was still throwing the same error. I also checked out my routes file which is fine because post_controller is working fine in development mode.

What I am doing wrong here?

Ruby gsub not replacing newline character

I have this code

str = @universal_claim_form.errors.full_messages.join
        str.gsub('Patient Contact Information: Value', 'Patient phone number') if str =~ /Patient Contact Information/
        debugger
        str.gsub("\\n", "<br/>")
        debugger
        flash.now[:error] = "Form has errors and was unable to be submitted.<br/> " << str

the first gsub replaces an unwanted message and the second gsub it meant to replace all the newline characters with html line breaks

at the first debugger line str = "PMP Validation failed. This happens when something you entered does not pass PMP specific validations.\\nPatient phone number: Value must be a 10 digit number"

and at the second debugger the line hasn't changed

what's even more weird is that I did this in irb at the command line and it worked

2.1.1 :001 > s = 'test'
 => "test"
2.1.1 :002 > s
 => "test"
2.1.1 :003 > s += '\ntest'
 => "test\\ntest"
2.1.1 :004 > s.gsub('\\n', '<br/>')
 => "test<br/>test"
2.1.1 :005 >