Thursday, 18 February 2016

' sysv-rc-conf ' Text based tool to configure process runlevel + Ubuntu

Firstly, the runlevels.
LSB 4.1.0
IDNameDescription
0HaltShuts down the system.
1Single-user modeMode for administrative tasks.
2Multi-user modeDoes not configure network interfaces and does not export networks services.
3Multi-user mode with networkingStarts the system normally.
4Not used/user-definableFor special purposes.
5Start the system normally with appropriate display manager (with GUI)Same as runlevel 3 + display manager.
6RebootReboots the system.

sudo apt-get install sysv-rc-conf

sysv-rc-conf a nice text based tool to on/off the process runlevel.


Thursday, 29 October 2015

IRB.start equivalent in Python

Well, If anytime you wish to use the IRB.start like feature of Ruby in Python.

They way to do it is.

import code
import readline


vars = globals() ## important to carry over the methods and variable define in program to shell
shell = code.InteractiveConsole(vars)
shell.interact()


Thursday, 2 July 2015

Some Ruby Thing

The following post consist of some features in ruby that are lesser known to people.

1. alias for '.call'

class Ticket
  def purchase
    puts "** Purchasing the Ticket **"
  end 
  alias_method :call,:purchase
end

## Following are they way you can invoke the download method
Ticket.new.purchase
## => ** Purchasing the Ticket **
A.new.call
## => ** Purchasing the Ticket **
A.new.()
## => ** Purchasing the Ticket **

2.  Disabling (SSL) Certificate Check from all Gems or Ruby Libraries.

unless Rails.env.production?
  class Net::HTTP
    def verify_mode=(verify_mode)
      @verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end  

Note:

  • Do this only on your local or development environment.
  • Also the above code only work if the libraries or gem uses 'Net::HTTP' API internally, 
  • Tested with HTTParty,Faraday,RestClient not working with Excon(so Excon adapter over Faraday might not work as well).




3. Locking a file using flock.
    Firstly I advise you to read through flock and also this amazing answer by Arjun Shankar.
 
flock (locking_constant )→ 0 or falseclick to toggle source
Locks or unlocks a file according to locking_constant (a logical or of the values in the table below). Returns false if File::LOCK_NB is specified and the operation would otherwise have blocked. Not available on all platforms.
Locking constants (in class File):
LOCK_EX   | Exclusive lock. Only one process may hold an
          | exclusive lock for a given file at a time.
----------+------------------------------------------------
LOCK_NB   | Don't block when locking. May be combined
          | with other lock options using logical or.
----------+------------------------------------------------
LOCK_SH   | Shared lock. Multiple processes may each hold a
          | shared lock for a given file at the same time.
----------+------------------------------------------------
LOCK_UN   | Unlock.
 

Example

open(file,'w+') do |file|
  ## lock the file so that no one can use it. 
  file.flock(File::LOCK_EX)
  read(file_name).each do |row|
    file.puts jsonify(row)
  end
end 


Thanks.

Tuesday, 21 April 2015

Use .wgetrc for default wget settings.

I use wget quite a lot and in the end I always end up using a large number of common options like

-c (to continue/resume a wget process)
--no-check-certificate (ignore ssl certificate check over https)

which eventually make it look very ugly but thanks to .wgetrc I no longer has to do it.

Create a .wgetrc file onto your home directory

JFI, Here how my current .wgetrc look.

continue=on     ## equivalent to -c options
check_certificate=off  ## equivalent to --no-check-certificate

Noting it down here so I just don't forget it future.

Thanks








Friday, 10 April 2015

Using HTTPProxy in Net/HTTP globally.

There comes a time when you want to Proxy your Net/HTTP request/response in Ruby.

One of the easy ways to do this in NET/HTTP is by passing proxy parameters in '.new'  method (during initialization)

proxy_addr = 'your.proxy.host'
proxy_port = 8080

Net::HTTP.new('example.com', nil, proxy_addr, proxy_port).start { |http|
  # always proxy via your.proxy.addr:8080
}

Obviously, this works but then querying the website using GET or GET BY URI method there is no provision to pass any proxy parameters altogether(at least that's what I found out.)

Thankfully Ruby-2.0+ (not available in lower versions though, can be seen over here) has a feature with which you can provide proxy as your ENV variable (http_proxy environment variable) and ruby take care of the rest.

So, upon setting  http_proxy in ENV I found, BAAM!!!  it worked and it worked globally (i.e it works even on GET and GET BY URL methods mentioned above.)

BTW, I had the following declaration inside my .bash_profile.


export http_proxy= 'http://127.0.0.1:8080'  (8080 is the port where my Squid Proxy is functional)


Thanks




Monday, 16 March 2015

Hack With Rack

Hello everyone, Hope you are having a good day.
Ok, some years ago, one of our clients wanted us to implement Social Network (FB,Twitter,Linkedin) sharing functionality. Knowing all the OAuth implementation that one has to deal with, we decided to use this awesome gem called OmniAuth that does all the heavy lifting tasks of OAuth Authorisation with very basic minimum implementation.
So with OmniAuth we manage to get the work done in time but then we wanted OAuth Authorisation to work with Ajax call as well. I remember going all out crazy (Googling + debugging OmniAuth code) to find a way to do it but honestly we couldn’t find any way do it. (Note: This was some years back I’m not sure about the status as of now.)
So we decide to write our own “Rack Middleware” that tampers with the Omniauth Response and treats the ajax request the way we wanted.
The Middleware

and then we insert the Middleware where we wanted it

Let look at our middleware stack

Yup that's it- a "Hack with Rack" to get a concrete solution for our problem that isn't too fancy but still does the task we needed getting done.

Sunday, 1 September 2013

Some Carrierwave Tip n Tricks

Finally wait is over I mean after nearly a rough patch of virtually no post for an year I back with a post again

As the title suggest it with regards to some tips and tricks that I manage to pull on carrierwave when working on a project

A) Upload Simultaneously to File and S3

I know there are tons of way to do this like upload the file first to server and then using the background process upload it to S3 blah blah .
Even directly upload to S3 is also an options since AMAZON S3 allow CORS

Well all this work great but I kind of not want to do them perhaps, may try some other approach
(Mind you nothing against the other approach mention thus after or already exists)

So what is my approach well basically nothing all you have to do customize your uploader a bit (not heavy customization though )

Consider this is your standard uploader look like  with default storage as :file

class MyUploader < CarrierWave::Uploader::Base
  storage :file
  ... blah ...
  ... blah ... 
  ... blah ... 
end
Now to simultaneously upload it to S3 all you have to do is place this in your uploader.
 version :s3_version do
     storage :fog
     def full_file_name
       super.sub(/s3_version_/,'')
     end
   end
So your uploader finally look like this
class MyUploader < CarrierWave::Uploader::Base
   storage :file
    ... blah ...
    ... blah ...

   version :s3_version do
     storage :fog
     def full_file_name
       super.sub(/s3_version_/,'')
     end
   end
end

That it define a version :s3_version (virtually any name you want) and then use storage as :fog in it (make sure to change the REGULAR EXPRESSION incase you chose a different version name other then s3_version)

Note : Also make sure to add the FOG setting for Carrierwave (S3 is just taken as an example it would work it all storage that fog provide)

Now most of you would argue that if say S3 isn't responding/ something goes wrong in S3 over net, then your local storage goes for a toss and I agree completely with that to so I urge viewer to please take a note of this . Well for me I happy taking that risk on my part . :)


B). Delete the record but don't delete the attachment

Well not all would agree with me on this but there are time when we been ask to delete the uploader record but not delete the file stored :)

There could be many reason like in my case there was a requirement that we need to retain the original copy of the client registered agreement even though the client not longer exists

As said there exists even a dozen tons of ways to achieve this as well but let me show you how I manage to pull off this.

All I did is I overwrite the method remove!  in my uploader and I also define a attr_accessor against my model (i.e attr_accessor :keep_file on my model)

Enough said time for code
class MyUploader < CarrierWave::Uploader::Base 
  def remove!
     unless model.keep_file
       super
     end
  end
end


Now to secure the storage file and only delete the record all I did is set  :keep_file => true and rest is taken care.

What I mean is record are destroyed but not the file from the storage system with this

There is another approach but I now tried and tested it that one would to overwrite the remove? 
method  something like this (Note I haven't tested this )
class MyUploader < CarrierWave::Uploader::Base 
  def remove?
    false
  end
end

C). Custom the CarrierWave Error Message

Ever since I question/answered my own question I'm seeing that I'm getting a lot of traction on it . What I have asked for is -

How to change the Carrierwave error message and set your own ?.

Well clearly the answer for that is define a key/value in your en.yml for desired carrierwave error message and that it

e.g Let say Carrierwave default message on extensions whilelists valdations is this
You are not allowed to upload %{extension} files, allowed types: %{allowed_types}

Now want is to change reason (reason with held with me :) ) . So all I have to do is this

in my en.yml define something like this
en:
  errors:
    messages:
       extension_white_list_error: 'My Custom Message'

A full list of carrierwave key/value pair can be found over here

That it guys hope you liked the tricks and found it useful

Thank You






What did I learn today?

Welcome to the what did I learn today series. The intention of this blog spot is to compose the stuff that I learnt day-to-day basics and jo...