How to Write Awesome code – Ruby on Rails – V1

Everyone wish to write the better code, But How, Is there any pattern / behaviour? Can anyone point to your code what can be improved?

The answer is YES, There is pattern you should follow the OOPS way by it’s core. I have written SOLID principle before this, Please check this too. I am going to write more series in this topic as it’s really interesting and helpful to everyone.

focus on one thing
Focus on one thing in a Class

In Ruby it’s damn easy but we don’t understand what mistake we are doing, so chances of improvement is less. So, Let’s take an example of below MyClass in code1 as below.

Code1:

class MyClass
  attr_reader :input
  
  def initialize(input)
    @input = input
  end

  def double
    case input
      when Numeric  then target . 2 
      when String   then target.next    # lazy fail ex
      when Array    then target.collect {|o| MyClass.new(o).double}
      else
        raise “don’t know how to double #{input.class} #{input.inspect}”
    end
  end
end

The result of the code1 is Output1 as below:

>> MyClass.new(‘aaa’).double
=> "aab"
>> MyClass.new(49).double
=> 98
>> MyClass.new([‘b’, 6]).double
=> ["c", 12]
>> MyClass.new({‘x’=>‘y’}).double
RuntimeError: don’t know how to double Hash {"x"=>"y"}
        from (irb):73:in `double'
        from (irb):80
        from :0

The above code looks Good, Right ?

You’re probably used / gone thought with this pattern. and, Its everywhere in Ruby on Rails.

But, This style of code is Absolutely Wrong and that you should do a different thing.

Why is the problem in above code?

If I change how double works on any of these classes, MyClass must change, but that’s not the real problem. What happens if MyClass wants to double some new kind of object? I have to go into MyClass and add a new branch to the case statement. How annoying is that?

But that’s the least of it. If I’m writing code that follows this pattern, I likely have many classes that do stuff based on the classes of their collaborators. My entire application behaves this way. Every time I add a new collaborating object I have to go change code everywhere. Each subsequent change makes things worse. My application is a teetering house of cards and eventually it will come tumbling down.

Also, what if some other wishes to use MyClass with their new SuperDuperClass object? They can’t reuse MyClass without changing it since MyClass has a very limited notion of what kinds of objects can be doubled.

MyClass is both rigid and closed for extension.

Code2:

class Numeric
  def double
    self * 2
  end
end

class String
  def double
    self.next 
  end
end

class Array
  def double
    collect {|e| e.double}
  end
end

class Object
  def double
    raise "don't know how to double #{self.class} #{self.inspect}"
  end
end

class MyClass
  attr_reader :input
  
  def initialize(input)
    @input = input
  end

  def double
    input.double
  end
end

What basically it should be as below (Something like this) :

Using this new code, Output1 will be the same as before, but now we can also use this way as output2:

Output2:

>> 'aaa'.double
=> "aab"
>> 49.double
=> 98
>> ['b', 6].double
=> ["c", 12]

In this above code2,

The Objects are what they are and because of that, they actually behave the way they do.

Above statement is very simple but incredibly important.

They tell each other what, not how.

What is the event/notification/request and it is the responsibility of the sender.(sender should know).

How is the behaviour/implementation and it should be completely hidden in the receiver (sender not required to know).

Therefore:

  • MyClass should not know how Numeric implements double.
  • MyClass should just ask target to double itself.
  • All possible targets must implement double.
  • Object should implement double to help you get your Ducks in a row.

Thanks for reading. For more information I highly recommend to read Sandi Metz books.

Courtesy 99 Bottles of OOP by Sandi Metz.

Sandi metz

Happy Learning & Coding!

Note: This concept can be used with any programming language.

SOLID Principle in Ruby on Rails

SOLID Stands for:

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

The acronym stands for principles to help software engineers to create / write maintainable source code for long-term that use an OOPS language.

Single responsibility principle: Focus on One thing in a Class Seprately.

Open/closed principle: Class should be open for extension and closed for modification.

 Liskov substitution principle: The derived class must be capable of being substituted by its base class.

Interface Segregation principle:

Interface Segregation Principle (1996)

Dependency Inversion principle (DIP): Now a days used with Docker, Docker composer.

The Dependency Inversion Principle

Simple Bubble Sort Algorithm in Ruby – Explained

Bubble

Can you write a Bubble sort in ruby?

The interviewer usually asks sorting algorithm and mostly the bubble sorting methods in the their interview. As that is one of the most commonly asked questions in sorting algorithm. So, I thought to share that in my blog here.

Bubble Sort

The bubble sort makes the larger elements (“big bubble”) towards the end and the smaller elements (“small bubble”) towards the starting point until all the elements reach in their correct location. i.e in proper sorted order from Small to Big sort.

# A method to define the bubble sort
def bubble_sort(array)
  # condition: When array has more than one element
  if array.count > 1
    swap = true
    # Loop: Run until swap is true
    while swap
      swap = false
      # Loop: Run loop with array counts and swap if 
      (array.length-1).times do |z|
        if array[z] > array[z+1]
          # swap if current number element is greater than next number element.
          array[z], array[z+1] =  array[z+1], array[z]
          # as we we have current number element is greater than next number element
          # so we updated more swap needed.
          swap = true
        end
      end
    end
    # While loop will stop once  array[z] > array[z+1] will be false 
    # then swap will become false line number 8.
  end
  array
end


print "Befor sort - #{[7,9,3,5,4,2,1]}"
print "\n"
print "After sort - #{bubble_sort([7,9,3,5,4,2,1])}"
print "\n"


When you will run the above code( Public Gist here). tath will Result as below:

bubble sorted result

Thank you!

To upgrade ruby 2.x to ruby 2.7 and rails 4.x to rails 6.0

Ruby on Rails update

It’s very rare to directly update from ruby 1.8.7 or ruby 2.0 to ruby 2.7 and rails 4 to rails 6.0. As I have recently done many upgrade projects from legacy ruby code to new ruby code. So, I thought to help other developers too.

How?

To do so, I have got the advantage of working from Ruby 2.x to the current version of ruby to I know each and everything from legacy plugin development age to gems and then gems to new replaced gems(if depreciated).

What?

For a small project, I would rather suggest installing a fresh project in the latest ruby and latest rails there. Now, I will replace the app folder of the old code into a new project.

also, I will keep adding configurations carefully as it’s mainly updated.

GEMS:

Regarding other gems, go to their GitHub documentation and check if the community is active (check using the last commit), if yes then you can install with their latest version without setting the gem version. i.e. gem install devise and add gem 'devise' in your Gemfile.

Migration:

and most important is the GEMS, from the old file, remove all ruby and rails related gems to transfer as new rails is already installed.

In migrations, you will have to add `[6.0]` in migration.

Webpacker update:

Ideally, we should use webpacker with rails 6, but As most clients don’t give time to re-write the javascript code with webpacker. So, It’s better to use normal javascript as in-app/assets folder.

And

For better projects management, we should follow the process:

  1. Prepare the List of Decreciated gems. Identify all possible new gems which can be used also if required or not.
  2. Prepare the documentation of changes required.
  3. Prepare the timelines accordingly.
  4. Work on ROR update as per your plan.
  5. Always use another branch for any kind of upgrades. and never use the master branch for an upgrade.
  6. Try to write the test cases as well so that you will be sure about the functionality is working properly.
ruby on rails

Feel free to let me know if you face any issue or wish me to work on your ruby on rails update. I will be happy to assist.

Thanks,

Manish S

SoX – Sound eXchange ubuntu commands

SoX is a cross-platform (Windows, Linux, MacOS X, etc.) command line utility that can convert various formats of computer audio files in to other formats. It can also apply various effects to these sound files, and, as an added bonus, SoX can play and record audio files on most platforms.

The screen-shot to the right shows an example of SoX first being used to process some audio, then being used to play some audio files.

10 Awesome Examples to Manipulate Audio Files Using Sound eXchange (SoX)

1. Combine Multiple Audio Files to Single File

using sox -m command mix the two audio file using terminal

$ sox -m first_part.wav second_part.wav whole_part.wav

(or)

$ soxmix first_part.wav second_part.wav whole_part.wav

2. Extract Part of the Audio File

Trim can trim off unwanted audio from the audio file. and set the custome starting and end time.

$ sox old.wav new.wav trim [SECOND TO START] [SECONDS DURATION].

  • SECOND TO START – Starting point in the voice file.
  • SECONDS DURATION – Duration of voice file to remove

The command below will extract first 15 seconds from input.wav and stored it in output.wav

$ sox input.wav output.wav trim 0 10

3. Increase and Decrease Volume Using Option -v

Option -v is used to change (increase or decrease ) the volume.

increase volume : –

$ sox -v 2.0 foo.wav bar.wav

decrease volume : –

$ sox -v -0.5 srcfile.wav test05.wav

$ sox -v -0.1 srcfile.wav test01.wav

4. Play an Audio Song

Sox provides the option for playing and recording sound files. This example explains how to play an audio file on Unix, Linux.

Syntax :play options Filename audio_effects

$ play -r 8000 -w music.wav

5. Play an Audio Song Backwards

Use the ‘reverse’ effect to reverse the sound in a sound file. This will reverse the file and store the result in output.wav

$ sox input.wav output.wav reverse

You can also use play command to hear the song in reverse without modifying the source file as shown below.

$ play test.wav reverse

6. Record a Voice File

You can also use rec command for recording voice. If SoX is invoked as ‘rec’ the default sound device is used as an input source.

$ rec -r 8000 -c 1 record_voice.wav

7. Changing the Sampling Rate of a Sound File

To change the sampling rate of a sound file, use option -r followed by the sample rate to use, in Hertz. Use the following example, to change the sampling rate of file ‘old.wav’ to 16000 Hz, and write the output to ‘new.wav’

$ sox old.wav -r 16000 new.wav

8. Changing the Sampling Size of a Sound File

If we increase the sampling size , we will get better quality. Sample Size for audio is most often expressed as 8 bits or 16 bits. 8bit audio is more often used for voice recording.

-b Sample data size in bytes
-w Sample data size in words
-l Sample data size in long words
-d Sample data size in double long words

$ sox -b input.wav -w output.wav

9. Changing the Number of Channels

The following example converts mono audio files to stereo.  Use Option -c to specify the number of channels .

$ sox stereo.wav -c 1 mono.wav avg -l

10. Speed up the Sound in an Audio File

To speed up or slow down the sound of a file, use speed to modify the pitch and the duration of the file. This raises the speed and reduces the time. The default factor is 1.0 which makes no change to the audio. 2.0 doubles speed, thus time length is cut by a half and pitch is one interval higher.

Syntax: sox input.wav output.wav speed factor

$ sox input.wav output.wav speed 2.0

Happy coding ..

Top 5 JavaScript framework for Web Developers

If you want to land a great JavaScript job or catch up on important tech for 2020 and important technologies in the new decade, this post is for you. The point of this post is not to tell you which tech stacks and frameworks are the “best” or most loved or most popular — but to shed some light on which ones give you the best odds of landing a great job in 2020 and beyond.It can be really hard to find the perfect framework for your requirements. In this article on the best JavaScript framework for 2020.

5 JavaScript frameworks : –

1. React js

React is a JavaScript library for building user interfaces. React js is most popular JavaScript frame work for front end web page designing and currently every front end developer react js is a first choice.

React is a front-end library developed by Facebook. It is used for handling the view layer for web and mobile apps. ReactJS allows us to create reusable UI components. It is currently one of the most popular JavaScript libraries and has a strong foundation and large community behind it.

2. Vue js

Vue js is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable.

The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

3. Angular js

Angular is one of the most powerful and open-source JavaScript frameworks. Google operates this framework and is designed to use it to develop a Single Page Application (SPA).

This development framework is known primarily because it gives developers the best conditions to combine JavaScript with HTML and CSS. Over half a million websites, such as google.com, youtube.com, etc., use Angular.

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

5, Node.js

Node.js is an open-source, server-side platform built on the Google Chrome JavaScript Engine. The number of websites. It is one of the most downloaded, cross-platform runtime environments for running JavaScript code.

Node.js is an asynchronous, single-threaded, non-blocking I/O model that makes it lightweight and efficient. The Node.js package ecosystem, npm, is also the largest open-source library ecosystem in the world.

Happy coding ….

#javascript #framework

Manish Shrivastava’s 5 Rules For Building A Successful Business

Manish Shrivastava is a Serial Entrepreneur. and helped many business persons and companies to become tycoon.
Manish shrivastava mantra of success

To follow successful strategy to become The successful Business-man, You must follow below Key Rules:

  1. Discipline:

    Everyone wish to gain more in their life only they lake in discipline and will power. They want to be consistent and follow planned path but, it is not easy.

    Everyone gets the 24 hours every day. Successful person use their time wisely, accurate and way balanced for work and their personnel life.

    Big goals need more disciplined routine. For long term, it will be touch and will need more focus and efforts.
    You can read more about the business discipline here.

  2. Dedication:

    To be disciplined, Dedication plays the key role. Your enthusiasm towards your business help you to achieve the success in the business.

  3. Clear Vision / Goal:

    Human mind is really dynamic when we think about some vision or our goal. It is surely distracting when you think more.
    Successful businessman always keep a vision, focused towards their goal.

  4. Planning and Execution path:

    When you have the clear goal and you work with discipline and dedication to achieve then you think around your idea most of the time. You do the planning around your idea and note them in proper manner. You decide the execution path and you are ready to go on success floor.
    Again, it is never easy otherwise everyone would have achieved their dreams.
    The negative mind will drag you down for laziness that stop you doing above things. But, If you are inspired enough and have good energy in your plan and focused then nothing in the world can stop you. Only your negative mind and laziness can stop you. But you can avoid that by your enthusiasm towards your goal.

  5. Read Your Market and Update yourself accordingly:

    Now, You are disciplined, have good dedication towards your single focused goal and your planning and execution is properly done.
    Most of the Successful businessman stopped here. and become obsolete with time. For example, Kodak Camra, Bajaj Scooter, HTML Watch etc.
    So, To become market fit and to become the business tycoon, you must analyse your market and continues work towards your improvement.
    Once you become steady (as human nature force to do so), then your progress become slow or sometime obsolete. So, You should update yourself by reading more books and getting know about the market research in your business fields.

Thank you

[Solved]: Incorrect datetime value: ‘0000-00-00 00:00:00’ for column

Problem faced: Incorrect datetime value: ‘0000-00-00 00:00:00’ for column.

Solution: The best way to do this is to export the MySQL dump file using below command from the database.

mysqldump -uroot -ppasswordname databasename > database_name.sql

Now, you have `database_name.sql` and try to open the file and search the string `0000-00-00 00:00:00` and replace it with `CURRENT_TIMESTAMP`. You can do that with below command:

sed -i.bu 's/'\''0000-00-00 00:00:00'\''/CURRENT_TIMESTAMP/g' database_name.sql

Once in your file when you replaced all `0000-00-00 00:00:00` with `CURRENT_TIMESTAMP`. You can import that into new separate MySQL 5.7 installed separately successfully.

However, there are different suggestion at stackoverflow. You can go through this if you need.

That’t it. You can test that and let me know if anything.

Cheers

About Me!

Manish loves coding.

Interesting Area:

Web Application / Hybrid Mobile Apps / ML Code / AI Code. He has very good experience (10+ years) in working on different technologies.

Technology:

ROR, React, Python, PHP, React Native.