Ruby vs Elixir , Rails vs Phoenix - part 1

2018-09-28 16:52:56 +0000

useful image

This is not a, “Which is better?”, post. It is more a way to help other developers, like myself, who have a background in Rails development and are interested in Elixir and Phoenix.

Elixir != Ruby and Phoenix != Rails. Even though there may be some similarities between both, it is beneficial to stay open to innovative and often lateral approaches in Elixir/Phoenix.

If you are a Ruby/Rails developer who is interested in adding Elixir/Phoenix to your toolbelt, then I hope this post serves as a helpful starting point.

class User < Struct.new(:first, :last)
  def self.full_name(user)
    "#{user.first} #{user.last}"
  end
end

user = User.new("George", "Tinix")
User.full_name(user) 
#=> "George Tinix"
 

Notice that we pass user to the full_name method. There are no “object instances” to call methods on in Elixir.

defmodule User do
  defstruct [:first, :last]

  def full_name(user) do
    "#{user.first} #{user.last}"
  end
end

user = %User{first: "George", last: "Tinix"}
User.full_name(user)
#=> "George Tinix"
 

Embrace Pattern Matching

In Ruby, conditionals are predominant, but in Elixir it is more favorable to use pattern matching.

In Ruby, you might see something like this:

def notify_user(user)
  if user.send_emails? do
   #Send emails
  end
end
 

In Elixir, we would use pattern matching against the data structure of the user argument:

 def notify_user(%User{send_emails?: true}) do
  #Send emails
end
def notify_user(user), do: user
 

The above example shows the use of pattern matching within function definitions but we can also use pattern matching to control the flow of logic.

In Rails, this could be considered the equivalent of returning a Result object for handling outcomes beyond just true or false.

In Elixir, you would utilize pattern matching on a function’s result. The following is quite common to see in Phoenix controllers:

 case MyApp.do_something() do
  {:ok, value}     -> # do stuff ...
  {:error, errors} -> # do different stuff...
end
 

Updating a rails password via the rails console

2018-08-07 16:47:20 +0000

I forgot one of my test passwords and realized I didn’t have a quick way to redo the password. There is a simple handful of commands fix this:

irb(main):001:0> u = User.find_by_id(1)
  User Load (3.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
=> #<User id: 1, name: "JJ Asghar", email: "jjasghar@gmail.com", created_at: "2014-04-18 17:46:48", updated_at: "2014-04-25 23:21:10", password_digest: "$2a$10$or/wJw1I8Wpf0lXNbtawveoQXETGJbUkv/VwXQXzn92r...", remember_token: "uUJTExCyt4mpAOpQWd4PMA">
irb(main):002:0> u
=> #<User id: 1, name: "JJ Asghar", email: "jjasghar@gmail.com", created_at: "2014-04-18 17:46:48", updated_at: "2014-04-25 23:21:10", password_digest: "$2a$10$or/wJw1I8Wpf0lXNbtawveoQXETGJbUkv/VwXQXzn92r...", remember_token: "uUJTExCyt4mpAOpQWd4PMA">
irb(main):003:0> u.password = "a_stupid_pa$$word"
=> "_stupid_pa$$word"
irb(main):004:0> u.password_confirmation = "a_stupid_pa$$word"
=> "_stupid_pa$$word"
irb(main):005:0> u.save
   (2.0ms)  BEGIN
  User Exists (12.2ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('jjasghar@gmail.com') AND "users"."id" != 1) LIMIT 1
   (15.8ms)  UPDATE "users" SET "password_digest" = '$2a$10$Za7prnrSthhE90AvB15BNOMl8sf3oL7onBpZ45nH/9skwHfn1EFA.', "remember_token" = 'zOZYjEVovO143qrX1yhibw', "updated_at" = '2014-04-25 23:24:39.329502' WHERE "users"."id" = 1
   (4.6ms)  COMMIT
=> true
irb(main):006:0>

As you can see, you need to create an object via a find_by_, in my case id and write it to u. After that I change the password key to a_stupid_pa$$word along with the password_confirmation. I then write it to the database via u.save.

spacemacs toggle-transparency

2018-02-26 19:01:21 +0000

Anything added via spacemacs/add-toggle or things available in SPC t and SPC T should be proper toggles. This way, you can toggle them in user-config if you want to change the default state.

Specifically, spacemacs/toggle-transparency (and the related spacemacs/toggle-transparent-frame) both open a micro-state (in addition to toggling the setting). This means, that, if you want to have a transparent frame by default, you cannot just add (spacemacs/toggle-transparency) to your .spacemacs, because it will open the micro-state instead of just toggling transparency.

I’m not sure what other toggles do this, if there are any at all.

Ah, for now, I’m using this code in my user-config as a workaround:

 ;; Transparency by default
  (set-frame-parameter (selected-frame) 'alpha
                       (cons dotspacemacs-active-transparency
                             dotspacemacs-inactive-transparency))

later , spacemas reload config

SPC f e R

if you want load theme

SPC T s and select theme and enter

How to Install Latest Nodejs & NPM on Debian

2018-02-01 11:48:03 +0000

npm installation not working under Debian Stretch

I just tried to install node and npm on Debian Stretch. I installed node like decribed here.

After installing nodejs-legacy too I got the node command working but npm command still won’t be found.

So, I tried to install it manually via apt-get install npm but it just tells me that it can’t find the package. Next I tried the “Fancy Install (Unix)” from npm repository which fails with…

install npm@latest
fetching: https://registry.npmjs.org/npm/-/npm-5.5.1.tgz
module.js:327
    throw err;
    ^

Error: Cannot find module '/tmp/npm.1272/package/bin/read-package-json.js'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Function.Module.runMain (module.js:441:10)
    at startup (node.js:140:18)
    at node.js:1043:3
added 1 package and removed 1 package in 0.45s
/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
/usr/bin/npx -> /usr/lib/node_modules/npm/bin/npx-cli.js
+ npm@5.5.1
updated 1 package in 1.21s
It worked

later I look this a solution I things so … and saw if install nvm and later install with nvm install npm ??? ok I go

open https://github.com/creationix/nvm install NVM Node Version Manager

Install script To install or update nvm, you can use the install script using cURL:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

or Wget

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash

The script clones the nvm repository to ~/.nvm and adds the source line to your profile (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc).

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

Note: On Linux, after running the install script, if you get nvm: command not found or see no feedback from your terminal after you type:

command -v nvm

or run

nvm --version

later you can run …

nvm install node
Downloading and installing node v9.5.0...
Downloading https://nodejs.org/dist/v9.5.0/node-v9.5.0-linux-x64.tar.xz...
######################################################################## 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v9.5.0 (npm v5.6.0)
Creating default alias: default -> node (-> v9.5.0)
 tinix  ~  node -v
v9.5.0

look this…

 tinix  ~  node -v
v9.5.0

problem solved..!!!

Ruby for Rails: Blocks

2018-01-30 12:06:31 +0000

This post is the first in a series of blog posts about Ruby for Rails beginners. These are specifically for Rails developers who want to solidify their grasp of the Ruby language.

More than a decade ago, I started learning Rails before I knew any Ruby. Rails is written in Ruby of course, so when writing Rails code you are writing Ruby code. But at the beginning, I didn’t fully understand how Ruby worked. And that’s fine. A lot of people started learning Rails and picked up Ruby along the way.

The “Ruby for Rails” series will help you learn Ruby to make you a better Rails programmer.

In this blog post, we’ll talk about blocks. Ruby blocks can be confusing to beginners but it’s important that you learn them because you’ll keep on using them on your Rails application.

One of the first code you’ll see with blocks is with loops.

(1..10).each do |i|
  puts i
end

The block is inside do and end. This code displays the numbers 1 to 10. When you read it, it kind of makes sense. From 1 to 10, for each i, puts i. If you have experience with other programming languages, you might think this is just a more complicated way to do loops.

each isn’t only for numbers. You can also iterate through an array.

["Alice", "Bob", "Eve"].each do |name|
  puts name
end

This code iterates through each element and prints the name. In Rails, you commonly use each when iterating through your model.

Post.all.each do |post|
  puts post.title
end

Say you have a Post model with a title. When you call each on Post.all , you iterate on each of those posts and the value is assigned to **post **which is inside || . Since post is a Post object, you can call post.title inside the block.

The examples so far show that blocks can be used to iterate through some objects. But the iteration is a by product of the each method. Blocks aren’t just for iteration. Here’s another common code in Rails.

<%= form_with Post.new do |form| %>
  <%= form.text_field :title %>
  <%= form.text_area :body %>
<% end %>
We use <%%> because this code appears on ERB templates. form_with is used to display an HTML form. Here, we call the form_with method and passes the Post.new parameter. form_with yields an object which we assign to form. You can use any variable inside   . We could have used f here instead of form.

In the examples above that used each, we yield each of the objects we’re iterating through. In form_with, we yield exactly one object which is the FormBuilder associated with the model. Inside the block you can use FormBuilder’s methods to generate fields like text_field, text_area, check_box, button, etc.

All the fields inside the block are captured and displayed inside the HTML form element.

These are just a few examples of blocks. You’ll see more when writing Rails code. So don’t get blocked out when coding!

I’d like this… original post by https://www.engineyard.com/blog/ruby-for-rails-blocks




subscribe via RSS