Edward Jackson

Edward Jackson

1560954448

Teaching a kid to code with Pygame Zero

As a software developer and father of two children, I think about this question often. A person with software skills can have big advantages in our modern world, so I’d like to equip my kids for their future.

In my home, we play video games together. My children (aged six and four) watch me play through many classics like Super Mario World and The Legend of Zelda: A Link to the Past. They like spending that time with daddy and are really engaged with the video game. When I considered how my six year old son might enjoy coding, using video games as the channel into computing was a very natural idea.

I’ve only recently explored game development myself so making a game with my son seemed like a great idea. When I asked him if he wanted to make a game, of course he said “YES!”

To Scratch or Not to Scratch

Once I confirmed his interest, it was time to figure out what to make. In the past, we tried out ScratchJr. ScratchJr uses a graphical interface and UI blocks to compose a set of actions. The tools that come with ScratchJr include looping, counting, and many of the other core things that belong in software development. My experience watching my son showed that ScratchJr was too far removed from programming.

ScratchJR user interface

At first, my son would drag little characters onto the screen and make them jump up and down or move from one side to the other. Later, his play transformed into using the application as a glorified paint program. He would record clips of his voice, change the colors of the characters, and mess around with the scene in countless other ways. I love art and have absolutely no issue with him pursuing artistic interests, but ScratchJr wasn’t teaching programming skills. I don’t know if the actions were too limited, or if he didn’t see the tool as a way to make interactive things.

When I considered our game project, the ScratchJr experience made me rule out Scratch, the more advanced version of building block programming. I also listened to an excellent episode of Talk Python To Me that helped re-enforce my belief that Scratch was not the path to take. In the episode, Michael interviewed Nicolas Tollervey about Teaching Python with the BBC micro:bit.

Nicholas made an awesome point that stuck with me. As a trained musician, he noted that musical instruction teaches kids on real instruments (albeit smaller to fit the size of children). Kids develop musical skills with real instruments, and these skills are directly transferible when a kid gets a larger version of the instrument as they grow. We know this system works because it’s how kids have learned instruments for hundreds of years. His point was this: if musical instruction demonstrates how to teach a kid a complex skill like playing an instrument, why shouldn’t we bring this strategy to teaching programming?

At that moment, I became convinced that the best service I could offer my son was to teach him with a programming language with all the features he would need. Naturally, as a long time Pythonista and user group organizer, Python was my obvious choice.

A Kid Running Python

I still had a lot of aspects of this project to figure out. What is the right user interface for a kid who doesn’t know how to touch type yet? Readers of my content may know that I’m a big Vim fan, but I certainly wouldn’t subject my son to that (yet! 😉 ).

Thankfully, there was more gold in that Talk Python To Me episode. Nicholas is also largely responsible for the Mu editor.

Mu user interface

Mu is an editor focused on running Python for beginners. Mu is awesome for beginners. Here are some highlights:

  • Python is included so there is no need to install something extra! This point probably cannot be overstated, because Python has a reputation for being complicated to install.
  • A number of popular packages like requests, matplotlib, and pyserial come preinstalled to lower the barrier further.
  • There is a mode to work directly with Adafruit’s CircuitPython to use hardware and microcontrollers in Python.
  • Game development is possible with the preinstalled Pygame Zero.

That final highlight is the clear reason why I chose to use Mu for my son.

Pygame Zero Versus Pygame

Pygame Zero is a tool for making video games. It is separate, but related to Pygame, a long-lived Python project that let’s you build (mostly 2-D) games using Python.

The differences between Pygame Zero and Pygame are related to the target audience. I think the Pygame Zero documentation states their project goal well:

[Pygame Zero] is intended for use in education, so that teachers can teach basic programming without needing to explain the Pygame API or write an event loop.
I mentioned at the start of this article that I was learning how to write games too. In my personal exploration of game development, Pygame was my primary choice for writing games. (Truthfully, I started with LÖVE to experiment with Lua and made a Pong clone, but I concluded Lua wasn’t for me.)

The short version of my experience with Pygame is that it’s not very beginner friendly. I’ve learned quite a bit about game development since I started a couple of years ago. When I view Pygame today, it seems more like a game library than a game engine. All the pieces are in place to make a game, but you have to wire everything together yourself. Long time game developers may love this flexibility, but it’s fairly overwhelming to new developers. And it would border on impossible for a six year old kid.

When I tried out Pygame Zero, I was surprised how different the experience was. Pygame Zero is much more like a game engine. The common pieces that you must handle yourself in Pygame are pre-wired in Pygame Zero. This dramatically lowers the barrier to entry, at the cost of flexibility. It’s absolutely the right trade-off for teaching.

What Did We Make?

After all that research, we made our first game in Pygame Zero. Let’s look at my son’s code, then explore the things he learned as well as the things I learned in the process.

First, here’s his entire first game.

slimearm = Actor('alien')
slimearm.topright = 0, 10

WIDTH = 712
HEIGHT = 508

def draw():
    screen.fill((240, 6, 253))
    slimearm.draw()

def update():
    slimearm.left += 2
    if slimearm.left > WIDTH:
        slimearm.right = 0

def on_mouse_down(pos):
    if slimearm.collidepoint(pos):
        set_alien_hurt()
    else:
        print("you missed me!")

def set_alien_hurt():
    print("Eek!")
    sounds.eep.play()
    slimearm.image = 'alien_hurt'
    clock.schedule_unique(set_alien_normal, 1.0)

def set_alien_normal():
    slimearm.image = 'alien'

And here’s a screenshot from the game running:

First game!

His entire game fits into 29 lines of code, including blank lines. In this 29 lines of code, he was able to learn an enormous amount of stuff. Also, to give credit where it is due, the game is a modified version of the one listed in the Pygame Zero introduction. If your eyes are hurting, you can thank my son for the hot pink color choice. The documentation used black, which might be a better fit for outer space.

What Did He Learn?

If you’ve been writing code for a long time, it’s super easy to forget the things that are hard or weird in programming.

Seeing a new programmer wrestle with core concepts is a great reminder that programming is hard, and we must be vigilant in our empathy to those who haven’t walked the path we walked.### Naming Things

In the very first line of the game, my son had to deal with variables.

slimearm = Actor('alien')

Variables (especially for someone who hasn’t done Algebra) are a pretty weird concept. I explained how variables are names for something else and how the name could be whatever we wanted. Because our program took many weekends to complete, we revisited the variables concept each time. Ultimately, I found that the best way to show how little the names mattered was to suggest we change the name alien in the documentation to something else. Thus, slimearm, his choice, was born.

Using a different variable name helped give him ownership of the code he wrote. We had conversations about how he would have to use his slimearm name instead of what he was seeing from the documentation page.

Mutability

My son also learned how malleable software can be. Pygame Zero made this extremely easy to show.

WIDTH = 712
HEIGHT = 508

Setting the window size for the game requires nothing more than changing WIDTH and HEIGHT. My son would:

  • Fiddle with the numbers.
  • Start the game to see the result, then stop it again.
  • Pick some crazy values.
  • Start the game to see a wacky window size.
  • Repeat until he was happy.

Now that I think about it, kids would make for amazing Quality Assurance engineers given their pension to explore and try things out.

Functions and Side Effects

I think what makes video games so magical as programs for teaching is the effects they produce.

Our industry has an odd obsession with thinking about side effects. Entire modes of programming try extremely hard to minimize side effects. What’s odd to me is that side effects like I/O or drawing to a screen are often the parts that we actually care about and want to see!

Games are really neat because they embrace side effects fully. Since the side effects show us that our code is doing things, they bring a lot of satisfaction.

When I got to the draw function, my son got what he came to see: the computer doing something that he wrote! These were the side effects in action.

def draw():
    screen.fill((240, 6, 253))
    slimearm.draw()

This draw function has no return statement. Each time you call it, the results will be different because of the state of slimearm. In other words, it fails to be a “purely functional” function since it has side effects. Maybe this makes higher education academics cringe, but it’s great for kids.

When we first started draw, we dealt with screen.fill as the first side effect. In my home, we’ve played with Arduino circuits regularly so my children know what LEDs are, and my son understands that an LED has red, green, and blue lights in it. I didn’t bother explaining tuples, but I told him that the three numbers to fill were RGB. We fired up Chrome DevTools, launched a color picker, and he dragged around until we found the “perfect” color.

Hoooooot pink!

State and Time

Before we could see the effects of slimearm.draw in the draw function, we needed to update the state of the alien to advance its position.

def update():
    slimearm.left += 2
    if slimearm.left > WIDTH:
        slimearm.right = 0

When I reached this stage, I had to find a method to explain how Pygame Zero alternates between draw and update to make the game run. It’s an example of the Update Method Pattern. 1

I used the idea of a filmstrip to illustrate the concept. In hindsight, this probably wasn’t the best metaphor since my son was born in 2012. We are well into the digital age for most video production so film is a rarity.

The game loop as a filmstrip

After I explained how film worked, my son latched onto the idea of frames as individual images that are drawn on the screen. We talked about how update is in between the frames and causing the frames to be different from each other. He seemed to understand the idea, but then we had to explore coordinates and (x, y) pairs and more concepts from Algebra that he has not studied yet!

So, I went back to the drawing board, literally. The best way I could think to explain how things worked in a 2D coordinate space was with a paper prototype.

Our paper prototype

Our paper prototype was an extremely useful visual tool. With the prototype, I made a game window and our alien character which I labeled as slimearm to match the variable name. Using the two separate pieces of paper, my son could see, in a very visual way, how the character would move. By anchoring on the filmstrip concept, we iterated through the game loop each frame. Since he could point to the various parts, like the left edge which advanced in the update method, he was able to understand how the computer changed the position of the alien.

The labels also helped him get a grasp on the conditional logic. By asking in each loop “Is slimearm’s left edge farther over than the window width?,” it became clear when the alien should be positioned back on the left side and with what edge of the sprite.

Interacting with the Game

Games aren’t really games until you can do something in them. The point of this game is to try and click the alien. If you click it, you’ll hear a little sound, and see the alien temporarily change into a hurt image.

def on_mouse_down(pos):
    if slimearm.collidepoint(pos):
        set_alien_hurt()
    else:
        print("you missed me!")

We started with the concept of events. Being a digital native, my son had no trouble with thinking about actions like touching a screen. It took a bit of explanation to understand a “mouse down” event, but we used the trusty print function to illustrate the idea quickly.

Mu’s game mode has a built-in console that you can see in the editor while the game is running. Our first version of the function above looked more like this:

def on_mouse_down(pos):
    print('You clicked!')

Even this simple level of interaction was enough to make my son light up. I’d try to talk to him about something, but he would start up the game and click around to see an endless stream of “You clicked!” messages show up in the console. It turns out that low tech feedback is enough to get kids really excited!

When we moved up to the full function, I had to explain collisions. Thankfully, the paper prototype made this easy because we could make a game out of the game. I told my son to pretend to play the game while I was the computer. I’d slide the alien cutout along and yell out “Eek!” or “You missed me!“ as he would try to tap on it. Not only did this make us both smile, but the idea of colliding was really natural because of the real world analogue.

def set_alien_hurt():
    print("Eek!")
    sounds.eep.play()
    slimearm.image = 'alien_hurt'
    clock.schedule_unique(set_alien_normal, 1.0)

When we got to the set_alien_hurt function, we were really dealing with the juice of the game by adding sound effects and changing sprite images. The trickiest part of this was to explain computer clocks and the purpose of the line:

    clock.schedule_unique(set_alien_normal, 1.0)

I’m still not sure if he latched onto this concept or not. Frankly, we had nearly everything working so his interest in adding more code waned rapidly. schedule_unique is a challenging bit of code. You need to understand that functions are things that can be passed around like variables. You also need to wrestle with the idea that set_alien_normal will be called some time in the future and not by code that you wrote. I didn’t belabor this point in the code because we definitely reached the limits of his curiosity.

That brings us to the end of his game code. My son covered:

  • Naming
  • Mutability
  • Functions and side effects
  • State and time, and
  • Interaction

That’s a pretty amazing list of topics for almost any programmer!

What Did I Learn?

Let’s close this out with some of my personal lessons as a teacher. Some of the lessons were reminders of things I knew, but some of these were new lessons. I’m a parent of a kid who is just starting to come into his own and take ownership of his learning, so I’m learning how to help him best.

Repetition, Repetition, Repetition

And one more time: repetition. For most of us, our brains don’t lock-on to concepts after the first exposure. We need to experience things repeatedly for the concepts to sink in. I saw this as my son grappled with variables. Each week as he recalled variables, I had to remind him of what they were for.

If I wasn’t prepared for this kind of behavior, it would be effortless to get irritated. Since I’ve dealt with variables for years, I am so far removed from that first exposure that I barely recall what it was like. Exercising patience was my solution when it felt like he wasn’t mastering concepts.

Feedback Is Critical

I observed that my son was most interested when the computer would do something based on his input. Whether it was showing colors, displaying text, making sounds, or whatever else, he would delight in those moments of feedback. This is what brought me satisfaction as well. Seeing the joy on your child’s face as they latch onto an idea is one of those rewards of being a parent. 2

Use Props

Kids learn in multiple ways. When I hit a wall explaining some ideas with words, switching to a paper prototype dramatically improved the education experience for both of us. Not only was it a quick craft we could do together, but it was a fabulous aide in this process.

Recognize the Limits

Do I think my son would be able to make a game on his own now? Certainly not. I had to remember that there are limits to how much he would retain as we made this game. I didn’t expect him to become an amazing programmer after we finished. This meant that when we ran into some of the harder concepts, I would push a little to make him stretch his thinking, but back off when it was clear he wasn’t ready for an idea yet.

Celebrate!

Anyone who knows me well will know that I can be fairly stoic. This was not the time to be stoic. Making a game comes with a certain amount of intrinsic reward, but I also wanted my son to see a very clear extrinsic reward. Learning to program is difficult and making something that works (even if it comes from a documentation tutorial) is a feat worth celebrating for sure.

How many kids manage to make their own functioning video game? I’m sure that number is small in the scheme of things. So, I tried my best to get out of my normally stoic shell and celebrate with my son. In doing that, he could appreciate what he accomplished with someone who understood the project and cares for him.

Now What?

It didn’t take long before he started to have ideas of his own about the next game that we can make together. That game is still in the planning and ideation phases, but he’s excited to work on one.

That’s exactly the outcome I was hoping for. My son now sees programming as a tool for making things. And, I think the world could use more makers.

If you’ve enjoyed this article, would you mind sharing it on Twitter or your favorite social media so that others have the chance to learn something too?

#python

What is GEEK

Buddha Community

Teaching a kid to code with Pygame Zero
Monty  Boehm

Monty Boehm

1675304280

How to Use Hotwire Rails

Introduction

We are back with another exciting and much-talked-about Rails tutorial on how to use Hotwire with the Rails application. This Hotwire Rails tutorial is an alternate method for building modern web applications that consume a pinch of JavaScript.

Rails 7 Hotwire is the default front-end framework shipped with Rails 7 after it was launched. It is used to represent HTML over the wire in the Rails application. Previously, we used to add a hotwire-rails gem in our gem file and then run rails hotwire: install. However, with the introduction of Rails 7, the gem got deprecated. Now, we use turbo-rails and stimulus rails directly, which work as Hotwire’s SPA-like page accelerator and Hotwire’s modest JavaScript framework.

What is Hotwire?

Hotwire is a package of different frameworks that help to build applications. It simplifies the developer’s work for writing web pages without the need to write JavaScript, and instead sending HTML code over the wire.

Introduction to The Hotwire Framework:

1. Turbo:

It uses simplified techniques to build web applications while decreasing the usage of JavaScript in the application. Turbo offers numerous handling methods for the HTML data sent over the wire and displaying the application’s data without actually loading the entire page. It helps to maintain the simplicity of web applications without destroying the single-page application experience by using the below techniques:

Turbo Frames: Turbo Frames help to load the different sections of our markup without any dependency as it divides the page into different contexts separately called frames and updates these frames individually.
Turbo Drive: Every link doesn’t have to make the entire page reload when clicked. Only the HTML contained within the tag will be displayed.
Turbo Streams: To add real-time features to the application, this technique is used. It helps to bring real-time data to the application using CRUD actions.

2. Stimulus

It represents the JavaScript framework, which is required when JS is a requirement in the application. The interaction with the HTML is possible with the help of a stimulus, as the controllers that help those interactions are written by a stimulus.

3. Strada

Not much information is available about Strada as it has not been officially released yet. However, it works with native applications, and by using HTML bridge attributes, interaction is made possible between web applications and native apps.

Simple diagrammatic representation of Hotwire Stack:

Hotwire Stack

Prerequisites For Hotwire Rails Tutorial

As we are implementing the Ruby on Rails Hotwire tutorial, make sure about the following installations before you can get started.

  • Ruby on Rails
  • Hotwire gem
  • PostgreSQL/SQLite (choose any one database)
  • Turbo Rails
  • Stimulus.js

Looking for an enthusiastic team of ROR developers to shape the vision of your web project?
Contact Bacancy today and hire Ruby developers to start building your dream project!

Create a new Rails Project

Find the following commands to create a rails application.

mkdir ~/projects/railshotwire
cd ~/projects/railshotwire
echo "source 'https://rubygems.org'" > Gemfile
echo "gem 'rails', '~> 7.0.0'" >> Gemfile
bundle install  
bundle exec rails new . --force -d=postgresql

Now create some files for the project, up till now no usage of Rails Hotwire can be seen.
Fire the following command in your terminal.

  • For creating a default controller for the application
echo "class HomeController < ApplicationController" > app/controllers/home_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating another controller for the application
echo "class OtherController < ApplicationController" > app/controllers/other_controller.rb
echo "end" >> app/controllers/home_controller.rb
  • For creating routes for the application
echo "Rails.application.routes.draw do" > config/routes.rb
echo '  get "home/index"' >> config/routes.rb
echo '  get "other/index"' >> config/routes.rb
echo '  root to: "home#index"' >> config/routes.rb
echo 'end' >> config/routes.rb
  • For creating a default view for the application
mkdir app/views/home
echo '<h1>This is Rails Hotwire homepage</h1>' > app/views/home/index.html.erb
echo '<div><%= link_to "Enter to other page", other_index_path %></div>' >> app/views/home/index.html.erb
  • For creating another view for the application
mkdir app/views/other
echo '<h1>This is Another page</h1>' > app/views/other/index.html.erb
echo '<div><%= link_to "Enter to home page", root_path %></div>' >> app/views/other/index.html.erb
  • For creating a database and schema.rb file for the application
bin/rails db:create
bin/rails db:migrate
  • For checking the application run bin/rails s and open your browser, your running application will have the below view.

Rails Hotwire Home Page

Additionally, you can clone the code and browse through the project. Here’s the source code of the repository: Rails 7 Hotwire application

Now, let’s see how Hotwire Rails can work its magic with various Turbo techniques.

Hotwire Rails: Turbo Drive

Go to your localhost:3000 on your web browser and right-click on the Inspect and open a Network tab of the DevTools of the browser.

Now click on go to another page link that appears on the home page to redirect from the home page to another page. In our Network tab, we can see that this action of navigation is achieved via XHR. It appears only the part inside HTML is reloaded, here neither the CSS is reloaded nor the JS is reloaded when the navigation action is performed.

Hotwire Rails Turbo Drive

By performing this action we can see that Turbo Drive helps to represent the HTML response without loading the full page and only follows redirect and reindeer HTML responses which helps to make the application faster to access.

Hotwire Rails: Turbo Frame

This technique helps to divide the current page into different sections called frames that can be updated separately independently when new data is added from the server.
Below we discuss the different use cases of Turbo frame like inline edition, sorting, searching, and filtering of data.

Let’s perform some practical actions to see the example of these use cases.

Make changes in the app/controllers/home_controller.rb file

#CODE

class HomeController < ApplicationController
   def turbo_frame_form
   end
   
   def turbo_frame submit
      extracted_anynumber = params[:any][:anynumber]
      render :turbo_frame_form, status: :ok, locals: {anynumber: extracted_anynumber,      comment: 'turbo_frame_submit ok' }
   end
end

Turbo Frame

Add app/views/home/turbo_frame_form.html.erb file to the application and add this content inside the file.

#CODE

<section>

    <%= turbo_frame_tag 'anyframe' do %>
            
      <div>
          <h2>Frame view</h2>
          <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
              <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
              <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
              <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
          <% end %>
      </div>
      <div>
        <h2>Data of the view</h2>
        <pre style="font-size: .7rem;"><%= JSON.pretty_generate(local_assigns) %></pre> 
      </div>
      
    <% end %>

</section>

Add the content inside file

Make some adjustments in routes.rb

#CODE

Rails.application.routes.draw do
  get 'home/index'
  get 'other/index'

  get '/home/turbo_frame_form' => 'home#turbo_frame_form', as: 'turbo_frame_form'
  post '/home/turbo_frame_submit' => 'home#turbo_frame_submit', as: 'turbo_frame_submit'


  root to: "home#index"
end
  • Next step is to change homepage view in app/views/home/index.html.erb

#CODE

<h1>This is Rails Hotwire home page</h1>
<div><%= link_to "Enter to other page", other_index_path %></div>

<%= turbo_frame_tag 'anyframe' do %>        
  <div>
      <h2>Home view</h2>
      <%= form_with scope: :any, url: turbo_frame_submit_path, local: true do |form| %>
          <%= form.label :anynumber, 'Type an integer (odd or even)', 'class' => 'my-0  d-inline'  %>
          <%= form.text_field :anynumber, type: 'number', 'required' => 'true', 'value' => "#{local_assigns[:anynumber] || 0}",  'aria-describedby' => 'anynumber' %>
          <%= form.submit 'Submit this number', 'id' => 'submit-number' %>
      <% end %>
  <div>
<% end %>

Change HomePage

After making all the changes, restart the rails server and refresh the browser, the default view will appear on the browser.

restart the rails serverNow in the field enter any digit, after entering the digit click on submit button, and as the submit button is clicked we can see the Turbo Frame in action in the below screen, we can observe that the frame part changed, the first title and first link didn’t move.

submit button is clicked

Hotwire Rails: Turbo Streams

Turbo Streams deliver page updates over WebSocket, SSE or in response to form submissions by only using HTML and a series of CRUD-like operations, you are free to say that either

  • Update the piece of HTML while responding to all the other actions like the post, put, patch, and delete except the GET action.
  • Transmit a change to all users, without reloading the browser page.

This transmit can be represented by a simple example.

  • Make changes in app/controllers/other_controller.rb file of rails application

#CODE

class OtherController < ApplicationController

  def post_something
    respond_to do |format|
      format.turbo_stream {  }
    end
  end

   end

file of rails application

Add the below line in routes.rb file of the application

#CODE

post '/other/post_something' => 'other#post_something', as: 'post_something'
Add the below line

Superb! Rails will now attempt to locate the app/views/other/post_something.turbo_stream.erb template at any moment the ‘/other/post_something’ endpoint is reached.

For this, we need to add app/views/other/post_something.turbo_stream.erb template in the rails application.

#CODE

<turbo-stream action="append" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>
Add template in the rails application

This states that the response will try to append the template of the turbo frame with ID “messages”.

Now change the index.html.erb file in app/views/other paths with the below content.

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 3rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post any message %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>
change the index.html.erb file
  • After making all the changes, restart the rails server and refresh the browser, and go to the other page.

go to the other page

  • Once the above screen appears, click on the Post any message button

Post any message button

This action shows that after submitting the response, the Turbo Streams help the developer to append the message, without reloading the page.

Another use case we can test is that rather than appending the message, the developer replaces the message. For that, we need to change the content of app/views/other/post_something.turbo_stream.erb template file and change the value of the action attribute from append to replace and check the changes in the browser.

#CODE

<turbo-stream action="replace" target="messages">
  <template>
    <div id="message_1">This changes the existing message!</div>
  </template>
</turbo-stream>

change the value of the action attributeWhen we click on Post any message button, the message that appear below that button will get replaced with the message that is mentioned in the app/views/other/post_something.turbo_stream.erb template

click on Post any message button

Stimulus

There are some cases in an application where JS is needed, therefore to cover those scenarios we require Hotwire JS tool. Hotwire has a JS tool because in some scenarios Turbo-* tools are not sufficient. But as we know that Hotwire is used to reduce the usage of JS in an application, Stimulus considers HTML as the single source of truth. Consider the case where we have to give elements on a page some JavaScript attributes, such as data controller, data-action, and data target. For that, a stimulus controller that can access elements and receive events based on those characteristics will be created.

Make a change in app/views/other/index.html.erb template file in rails application

#CODE

<h1>This is Another page</h1>
<div><%= link_to "Enter to home page", root_path %></div>

<div style="margin-top: 2rem;">
  <%= form_with scope: :any, url: post_something_path do |form| %>
      <%= form.submit 'Post something' %>
  <% end %>
  <turbo-frame id="messages">
    <div>An empty message</div>
  </turbo-frame>
</div>

<div style="margin-top: 2rem;">
  <h2>Stimulus</h2>  
  <div data-controller="hello">
    <input data-hello-target="name" type="text">
    <button data-action="click->hello#greet">
      Greet
    </button>
    <span data-hello-target="output">
    </span>
  </div>
</div>

Make A changeMake changes in the hello_controller.js in path app/JavaScript/controllers and add a stimulus controller in the file, which helps to bring the HTML into life.

#CODE

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = [ "name", "output" ]

  greet() {
    this.outputTarget.textContent =
      `Hello, ${this.nameTarget.value}!`
  }
}

add a stimulus controller in the fileGo to your browser after making the changes in the code and click on Enter to other page link which will navigate to the localhost:3000/other/index page there you can see the changes implemented by the stimulus controller that is designed to augment your HTML with just enough behavior to make it more responsive.

With just a little bit of work, Turbo and Stimulus together offer a complete answer for applications that are quick and compelling.

Using Rails 7 Hotwire helps to load the pages at a faster speed and allows you to render templates on the server, where you have access to your whole domain model. It is a productive development experience in ROR, without compromising any of the speed or responsiveness associated with SPA.

Conclusion

We hope you were satisfied with our Rails Hotwire tutorial. Write to us at service@bacancy.com for any query that you want to resolve, or if you want us to share a tutorial on your query.

For more such solutions on RoR, check out our Ruby on Rails Tutorials. We will always strive to amaze you and cater to your needs.

Original article source at: https://www.bacancytechnology.com/

#rails #ruby 

Perl Critic: The Leading Static analyzer for Perl

BUILD STATUS

NAME

Perl::Critic - Critique Perl source code for best-practices.

SYNOPSIS

use Perl::Critic;
my $file = shift;
my $critic = Perl::Critic->new();
my @violations = $critic->critique($file);
print @violations;

DESCRIPTION

Perl::Critic is an extensible framework for creating and applying coding standards to Perl source code. Essentially, it is a static source code analysis engine. Perl::Critic is distributed with a number of Perl::Critic::Policy modules that attempt to enforce various coding guidelines. Most Policy modules are based on Damian Conway's book Perl Best Practices. However, Perl::Critic is not limited to PBP and will even support Policies that contradict Conway. You can enable, disable, and customize those Polices through the Perl::Critic interface. You can also create new Policy modules that suit your own tastes.

For a command-line interface to Perl::Critic, see the documentation for perlcritic. If you want to integrate Perl::Critic with your build process, Test::Perl::Critic provides an interface that is suitable for test programs. Also, Test::Perl::Critic::Progressive is useful for gradually applying coding standards to legacy code. For the ultimate convenience (at the expense of some flexibility) see the criticism pragma.

If you'd like to try Perl::Critic without installing anything, there is a web-service available at http://perlcritic.com. The web-service does not yet support all the configuration features that are available in the native Perl::Critic API, but it should give you a good idea of what it does.

Also, ActivePerl includes a very slick graphical interface to Perl-Critic called perlcritic-gui. You can get a free community edition of ActivePerl from http://www.activestate.com.

PREREQUISITES

Perl::Critic runs on Perl back to Perl 5.6.1. It relies on the PPI module to do the heavy work of parsing Perl.

INTERFACE SUPPORT

The Perl::Critic module is considered to be a public class. Any changes to its interface will go through a deprecation cycle.

CONSTRUCTOR

new( [ -profile => $FILE, -severity => $N, -theme => $string, -include => \@PATTERNS, -exclude => \@PATTERNS, -top => $N, -only => $B, -profile-strictness => $PROFILE_STRICTNESS_{WARN|FATAL|QUIET}, -force => $B, -verbose => $N ], -color => $B, -pager => $string, -allow-unsafe => $B, -criticism-fatal => $B)

new()

Returns a reference to a new Perl::Critic object. Most arguments are just passed directly into Perl::Critic::Config, but I have described them here as well. The default value for all arguments can be defined in your .perlcriticrc file. See the "CONFIGURATION" section for more information about that. All arguments are optional key-value pairs as follows:

-profile is a path to a configuration file. If $FILE is not defined, Perl::Critic::Config attempts to find a .perlcriticrc configuration file in the current directory, and then in your home directory. Alternatively, you can set the PERLCRITIC environment variable to point to a file in another location. If a configuration file can't be found, or if $FILE is an empty string, then all Policies will be loaded with their default configuration. See "CONFIGURATION" for more information.

-severity is the minimum severity level. Only Policy modules that have a severity greater than $N will be applied. Severity values are integers ranging from 1 (least severe violations) to 5 (most severe violations). The default is 5. For a given -profile, decreasing the -severity will usually reveal more Policy violations. You can set the default value for this option in your .perlcriticrc file. Users can redefine the severity level for any Policy in their .perlcriticrc file. See "CONFIGURATION" for more information.

If it is difficult for you to remember whether severity "5" is the most or least restrictive level, then you can use one of these named values:

  SEVERITY NAME   ...is equivalent to...   SEVERITY NUMBER
  --------------------------------------------------------
  -severity => 'gentle'                     -severity => 5
  -severity => 'stern'                      -severity => 4
  -severity => 'harsh'                      -severity => 3
  -severity => 'cruel'                      -severity => 2
  -severity => 'brutal'                     -severity => 1

The names reflect how severely the code is criticized: a gentle criticism reports only the most severe violations, and so on down to a brutal criticism which reports even the most minor violations.

-theme is special expression that determines which Policies to apply based on their respective themes. For example, the following would load only Policies that have a 'bugs' AND 'pbp' theme:

  my $critic = Perl::Critic->new( -theme => 'bugs && pbp' );

Unless the -severity option is explicitly given, setting -theme silently causes the -severity to be set to 1. You can set the default value for this option in your .perlcriticrc file. See the "POLICY THEMES" section for more information about themes.

-include is a reference to a list of string @PATTERNS. Policy modules that match at least one m/$PATTERN/ixms will always be loaded, irrespective of all other settings. For example:

  my $critic = Perl::Critic->new(-include => ['layout'], -severity => 4);

This would cause Perl::Critic to apply all the CodeLayout::* Policy modules even though they have a severity level that is less than 4. You can set the default value for this option in your .perlcriticrc file. You can also use -include in conjunction with the -exclude option. Note that -exclude takes precedence over -include when a Policy matches both patterns.

-exclude is a reference to a list of string @PATTERNS. Policy modules that match at least one m/$PATTERN/ixms will not be loaded, irrespective of all other settings. For example:

  my $critic = Perl::Critic->new(-exclude => ['strict'], -severity => 1);

This would cause Perl::Critic to not apply the RequireUseStrict and ProhibitNoStrict Policy modules even though they have a severity level that is greater than 1. You can set the default value for this option in your .perlcriticrc file. You can also use -exclude in conjunction with the -include option. Note that -exclude takes precedence over -include when a Policy matches both patterns.

-single-policy is a string PATTERN. Only one policy that matches m/$PATTERN/ixms will be used. Policies that do not match will be excluded. This option has precedence over the -severity, -theme, -include, -exclude, and -only options. You can set the default value for this option in your .perlcriticrc file.

-top is the maximum number of Violations to return when ranked by their severity levels. This must be a positive integer. Violations are still returned in the order that they occur within the file. Unless the -severity option is explicitly given, setting -top silently causes the -severity to be set to 1. You can set the default value for this option in your .perlcriticrc file.

-only is a boolean value. If set to a true value, Perl::Critic will only choose from Policies that are mentioned in the user's profile. If set to a false value (which is the default), then Perl::Critic chooses from all the Policies that it finds at your site. You can set the default value for this option in your .perlcriticrc file.

-profile-strictness is an enumerated value, one of "$PROFILE_STRICTNESS_WARN" in Perl::Critic::Utils::Constants (the default), "$PROFILE_STRICTNESS_FATAL" in Perl::Critic::Utils::Constants, and "$PROFILE_STRICTNESS_QUIET" in Perl::Critic::Utils::Constants. If set to "$PROFILE_STRICTNESS_FATAL" in Perl::Critic::Utils::Constants, Perl::Critic will make certain warnings about problems found in a .perlcriticrc or file specified via the -profile option fatal. For example, Perl::Critic normally only warns about profiles referring to non-existent Policies, but this value makes this situation fatal. Correspondingly, "$PROFILE_STRICTNESS_QUIET" in Perl::Critic::Utils::Constants makes Perl::Critic shut up about these things.

-force is a boolean value that controls whether Perl::Critic observes the magical "## no critic" annotations in your code. If set to a true value, Perl::Critic will analyze all code. If set to a false value (which is the default) Perl::Critic will ignore code that is tagged with these annotations. See "BENDING THE RULES" for more information. You can set the default value for this option in your .perlcriticrc file.

-verbose can be a positive integer (from 1 to 11), or a literal format specification. See Perl::Critic::Violation for an explanation of format specifications. You can set the default value for this option in your .perlcriticrc file.

-unsafe directs Perl::Critic to allow the use of Policies that are marked as "unsafe" by the author. Such policies may compile untrusted code or do other nefarious things.

-color and -pager are not used by Perl::Critic but is provided for the benefit of perlcritic.

-criticism-fatal is not used by Perl::Critic but is provided for the benefit of criticism.

-color-severity-highest, -color-severity-high, -color-severity- medium, -color-severity-low, and -color-severity-lowest are not used by Perl::Critic, but are provided for the benefit of perlcritic. Each is set to the Term::ANSIColor color specification to be used to display violations of the corresponding severity.

-files-with-violations and -files-without-violations are not used by Perl::Critic, but are provided for the benefit of perlcritic, to cause only the relevant filenames to be displayed.

METHODS

critique( $source_code )

Runs the $source_code through the Perl::Critic engine using all the Policies that have been loaded into this engine. If $source_code is a scalar reference, then it is treated as a string of actual Perl code. If $source_code is a reference to an instance of PPI::Document, then that instance is used directly. Otherwise, it is treated as a path to a local file containing Perl code. This method returns a list of Perl::Critic::Violation objects for each violation of the loaded Policies. The list is sorted in the order that the Violations appear in the code. If there are no violations, this method returns an empty list.

add_policy( -policy => $policy_name, -params => \%param_hash )

Creates a Policy object and loads it into this Critic. If the object cannot be instantiated, it will throw a fatal exception. Otherwise, it returns a reference to this Critic.

-policy is the name of a Perl::Critic::Policy subclass module. The 'Perl::Critic::Policy' portion of the name can be omitted for brevity. This argument is required.

-params is an optional reference to a hash of Policy parameters. The contents of this hash reference will be passed into to the constructor of the Policy module. See the documentation in the relevant Policy module for a description of the arguments it supports.

policies()

Returns a list containing references to all the Policy objects that have been loaded into this engine. Objects will be in the order that they were loaded.

config()

Returns the Perl::Critic::Config object that was created for or given to this Critic.

statistics()

Returns the Perl::Critic::Statistics object that was created for this Critic. The Statistics object accumulates data for all files that are analyzed by this Critic.

FUNCTIONAL INTERFACE

For those folks who prefer to have a functional interface, The critique method can be exported on request and called as a static function. If the first argument is a hashref, its contents are used to construct a new Perl::Critic object internally. The keys of that hash should be the same as those supported by the Perl::Critic::new() method. Here are some examples:

use Perl::Critic qw(critique);

# Use default parameters...
@violations = critique( $some_file );

# Use custom parameters...
@violations = critique( {-severity => 2}, $some_file );

# As a one-liner
%> perl -MPerl::Critic=critique -e 'print critique(shift)' some_file.pm

None of the other object-methods are currently supported as static functions. Sorry.

CONFIGURATION

Most of the settings for Perl::Critic and each of the Policy modules can be controlled by a configuration file. The default configuration file is called .perlcriticrc. Perl::Critic will look for this file in the current directory first, and then in your home directory. Alternatively, you can set the PERLCRITIC environment variable to explicitly point to a different file in another location. If none of these files exist, and the -profile option is not given to the constructor, then all the modules that are found in the Perl::Critic::Policy namespace will be loaded with their default configuration.

The format of the configuration file is a series of INI-style blocks that contain key-value pairs separated by '='. Comments should start with '#' and can be placed on a separate line or after the name-value pairs if you desire.

Default settings for Perl::Critic itself can be set before the first named block. For example, putting any or all of these at the top of your configuration file will set the default value for the corresponding constructor argument.

severity  = 3                                     #Integer or named level
only      = 1                                     #Zero or One
force     = 0                                     #Zero or One
verbose   = 4                                     #Integer or format spec
top       = 50                                    #A positive integer
theme     = (pbp || security) && bugs             #A theme expression
include   = NamingConventions ClassHierarchies    #Space-delimited list
exclude   = Variables  Modules::RequirePackage    #Space-delimited list
criticism-fatal = 1                               #Zero or One
color     = 1                                     #Zero or One
allow-unsafe = 1                                  #Zero or One
pager     = less                                  #pager to pipe output to

The remainder of the configuration file is a series of blocks like this:

[Perl::Critic::Policy::Category::PolicyName]
severity = 1
set_themes = foo bar
add_themes = baz
maximum_violations_per_document = 57
arg1 = value1
arg2 = value2

Perl::Critic::Policy::Category::PolicyName is the full name of a module that implements the policy. The Policy modules distributed with Perl::Critic have been grouped into categories according to the table of contents in Damian Conway's book Perl Best Practices. For brevity, you can omit the 'Perl::Critic::Policy' part of the module name.

severity is the level of importance you wish to assign to the Policy. All Policy modules are defined with a default severity value ranging from 1 (least severe) to 5 (most severe). However, you may disagree with the default severity and choose to give it a higher or lower severity, based on your own coding philosophy. You can set the severity to an integer from 1 to 5, or use one of the equivalent names:

SEVERITY NAME ...is equivalent to... SEVERITY NUMBER
----------------------------------------------------
gentle                                             5
stern                                              4
harsh                                              3
cruel                                              2
brutal                                             1

The names reflect how severely the code is criticized: a gentle criticism reports only the most severe violations, and so on down to a brutal criticism which reports even the most minor violations.

set_themes sets the theme for the Policy and overrides its default theme. The argument is a string of one or more whitespace-delimited alphanumeric words. Themes are case-insensitive. See "POLICY THEMES" for more information.

add_themes appends to the default themes for this Policy. The argument is a string of one or more whitespace-delimited words. Themes are case- insensitive. See "POLICY THEMES" for more information.

maximum_violations_per_document limits the number of Violations the Policy will return for a given document. Some Policies have a default limit; see the documentation for the individual Policies to see whether there is one. To force a Policy to not have a limit, specify "no_limit" or the empty string for the value of this parameter.

The remaining key-value pairs are configuration parameters that will be passed into the constructor for that Policy. The constructors for most Policy objects do not support arguments, and those that do should have reasonable defaults. See the documentation on the appropriate Policy module for more details.

Instead of redefining the severity for a given Policy, you can completely disable a Policy by prepending a '-' to the name of the module in your configuration file. In this manner, the Policy will never be loaded, regardless of the -severity given to the Perl::Critic constructor.

A simple configuration might look like this:

#--------------------------------------------------------------
# I think these are really important, so always load them

[TestingAndDebugging::RequireUseStrict]
severity = 5

[TestingAndDebugging::RequireUseWarnings]
severity = 5

#--------------------------------------------------------------
# I think these are less important, so only load when asked

[Variables::ProhibitPackageVars]
severity = 2

[ControlStructures::ProhibitPostfixControls]
allow = if unless  # My custom configuration
severity = cruel   # Same as "severity = 2"

#--------------------------------------------------------------
# Give these policies a custom theme.  I can activate just
# these policies by saying `perlcritic -theme larry`

[Modules::RequireFilenameMatchesPackage]
add_themes = larry

[TestingAndDebugging::RequireTestLables]
add_themes = larry curly moe

#--------------------------------------------------------------
# I do not agree with these at all, so never load them

[-NamingConventions::Capitalization]
[-ValuesAndExpressions::ProhibitMagicNumbers]

#--------------------------------------------------------------
# For all other Policies, I accept the default severity,
# so no additional configuration is required for them.

For additional configuration examples, see the perlcriticrc file that is included in this examples directory of this distribution.

Damian Conway's own Perl::Critic configuration is also included in this distribution as examples/perlcriticrc-conway.

THE POLICIES

A large number of Policy modules are distributed with Perl::Critic. They are described briefly in the companion document Perl::Critic::PolicySummary and in more detail in the individual modules themselves. Say "perlcritic -doc PATTERN" to see the perldoc for all Policy modules that match the regex m/PATTERN/ixms

There are a number of distributions of additional policies on CPAN. If Perl::Critic doesn't contain a policy that you want, some one may have already written it. See the "SEE ALSO" section below for a list of some of these distributions.

POLICY THEMES

Each Policy is defined with one or more "themes". Themes can be used to create arbitrary groups of Policies. They are intended to provide an alternative mechanism for selecting your preferred set of Policies. For example, you may wish disable a certain subset of Policies when analyzing test programs. Conversely, you may wish to enable only a specific subset of Policies when analyzing modules.

The Policies that ship with Perl::Critic have been broken into the following themes. This is just our attempt to provide some basic logical groupings. You are free to invent new themes that suit your needs.

THEME             DESCRIPTION
--------------------------------------------------------------------------
core              All policies that ship with Perl::Critic
pbp               Policies that come directly from "Perl Best Practices"
bugs              Policies that that prevent or reveal bugs
certrec           Policies that CERT recommends
certrule          Policies that CERT considers rules
maintenance       Policies that affect the long-term health of the code
cosmetic          Policies that only have a superficial effect
complexity        Policies that specifically relate to code complexity
security          Policies that relate to security issues
tests             Policies that are specific to test programs

Any Policy may fit into multiple themes. Say "perlcritic -list" to get a listing of all available Policies and the themes that are associated with each one. You can also change the theme for any Policy in your .perlcriticrc file. See the "CONFIGURATION" section for more information about that.

Using the -theme option, you can create an arbitrarily complex rule that determines which Policies will be loaded. Precedence is the same as regular Perl code, and you can use parentheses to enforce precedence as well. Supported operators are:

Operator    Alternative    Example
-----------------------------------------------------------------
&&          and            'pbp && core'
||          or             'pbp || (bugs && security)'
!           not            'pbp && ! (portability || complexity)'

Theme names are case-insensitive. If the -theme is set to an empty string, then it evaluates as true all Policies.

BENDING THE RULES

Perl::Critic takes a hard-line approach to your code: either you comply or you don't. In the real world, it is not always practical (nor even possible) to fully comply with coding standards. In such cases, it is wise to show that you are knowingly violating the standards and that you have a Damn Good Reason (DGR) for doing so.

To help with those situations, you can direct Perl::Critic to ignore certain lines or blocks of code by using annotations:

require 'LegacyLibaray1.pl';  ## no critic
require 'LegacyLibrary2.pl';  ## no critic

for my $element (@list) {

    ## no critic

    $foo = "";               #Violates 'ProhibitEmptyQuotes'
    $barf = bar() if $foo;   #Violates 'ProhibitPostfixControls'
    #Some more evil code...

    ## use critic

    #Some good code...
    do_something($_);
}

The "## no critic" annotations direct Perl::Critic to ignore the remaining lines of code until a "## use critic" annotation is found. If the "## no critic" annotation is on the same line as a code statement, then only that line of code is overlooked. To direct perlcritic to ignore the "## no critic" annotations, use the --force option.

A bare "## no critic" annotation disables all the active Policies. If you wish to disable only specific Policies, add a list of Policy names as arguments, just as you would for the "no strict" or "no warnings" pragmas. For example, this would disable the ProhibitEmptyQuotes and ProhibitPostfixControls policies until the end of the block or until the next "## use critic" annotation (whichever comes first):

## no critic (EmptyQuotes, PostfixControls)

# Now exempt from ValuesAndExpressions::ProhibitEmptyQuotes
$foo = "";

# Now exempt ControlStructures::ProhibitPostfixControls
$barf = bar() if $foo;

# Still subjected to ValuesAndExpression::RequireNumberSeparators
$long_int = 10000000000;

Since the Policy names are matched against the "## no critic" arguments as regular expressions, you can abbreviate the Policy names or disable an entire family of Policies in one shot like this:

## no critic (NamingConventions)

# Now exempt from NamingConventions::Capitalization
my $camelHumpVar = 'foo';

# Now exempt from NamingConventions::Capitalization
sub camelHumpSub {}

The argument list must be enclosed in parentheses or brackets and must contain one or more comma-separated barewords (e.g. don't use quotes). The "## no critic" annotations can be nested, and Policies named by an inner annotation will be disabled along with those already disabled an outer annotation.

Some Policies like Subroutines::ProhibitExcessComplexity apply to an entire block of code. In those cases, the "## no critic" annotation must appear on the line where the violation is reported. For example:

sub complicated_function {  ## no critic (ProhibitExcessComplexity)
    # Your code here...
}

Policies such as Documentation::RequirePodSections apply to the entire document, in which case violations are reported at line 1.

Use this feature wisely. "## no critic" annotations should be used in the smallest possible scope, or only on individual lines of code. And you should always be as specific as possible about which Policies you want to disable (i.e. never use a bare "## no critic"). If Perl::Critic complains about your code, try and find a compliant solution before resorting to this feature.

THE Perl::Critic PHILOSOPHY

Coding standards are deeply personal and highly subjective. The goal of Perl::Critic is to help you write code that conforms with a set of best practices. Our primary goal is not to dictate what those practices are, but rather, to implement the practices discovered by others. Ultimately, you make the rules -- Perl::Critic is merely a tool for encouraging consistency. If there is a policy that you think is important or that we have overlooked, we would be very grateful for contributions, or you can simply load your own private set of policies into Perl::Critic.

EXTENDING THE CRITIC

The modular design of Perl::Critic is intended to facilitate the addition of new Policies. You'll need to have some understanding of PPI, but most Policy modules are pretty straightforward and only require about 20 lines of code. Please see the Perl::Critic::DEVELOPER file included in this distribution for a step-by-step demonstration of how to create new Policy modules.

If you develop any new Policy modules, feel free to send them to <team@perlcritic.com> and I'll be happy to consider putting them into the Perl::Critic distribution. Or if you would like to work on the Perl::Critic project directly, you can fork our repository at https://github.com/Perl-Critic/Perl-Critic.git.

The Perl::Critic team is also available for hire. If your organization has its own coding standards, we can create custom Policies to enforce your local guidelines. Or if your code base is prone to a particular defect pattern, we can design Policies that will help you catch those costly defects before they go into production. To discuss your needs with the Perl::Critic team, just contact <team@perlcritic.com>.

PREREQUISITES

Perl::Critic requires the following modules:

B::Keywords

Config::Tiny

Exception::Class

File::Spec

File::Spec::Unix

File::Which

IO::String

List::SomeUtils

List::Util

Module::Pluggable

Perl::Tidy

Pod::Spell

PPI

Pod::PlainText

Pod::Select

Pod::Usage

Readonly

Scalar::Util

String::Format

Task::Weaken

Term::ANSIColor

Text::ParseWords

version

CONTACTING THE DEVELOPMENT TEAM

You are encouraged to subscribe to the public mailing list at https://groups.google.com/d/forum/perl-critic. At least one member of the development team is usually hanging around in irc://irc.perl.org/#perlcritic and you can follow Perl::Critic on Twitter, at https://twitter.com/perlcritic.

SEE ALSO

There are a number of distributions of additional Policies available. A few are listed here:

Perl::Critic::More

Perl::Critic::Bangs

Perl::Critic::Lax

Perl::Critic::StricterSubs

Perl::Critic::Swift

Perl::Critic::Tics

These distributions enable you to use Perl::Critic in your unit tests:

Test::Perl::Critic

Test::Perl::Critic::Progressive

There is also a distribution that will install all the Perl::Critic related modules known to the development team:

Task::Perl::Critic

BUGS

Scrutinizing Perl code is hard for humans, let alone machines. If you find any bugs, particularly false-positives or false-negatives from a Perl::Critic::Policy, please submit them at https://github.com/Perl-Critic/Perl-Critic/issues. Thanks.

CREDITS

Adam Kennedy - For creating PPI, the heart and soul of Perl::Critic.

Damian Conway - For writing Perl Best Practices, finally :)

Chris Dolan - For contributing the best features and Policy modules.

Andy Lester - Wise sage and master of all-things-testing.

Elliot Shank - The self-proclaimed quality freak.

Giuseppe Maxia - For all the great ideas and positive encouragement.

and Sharon, my wife - For putting up with my all-night code sessions.

Thanks also to the Perl Foundation for providing a grant to support Chris Dolan's project to implement twenty PBP policies. http://www.perlfoundation.org/april_1_2007_new_grant_awards

Thanks also to this incomplete laundry list of folks who have contributed to Perl::Critic in some way: Gregory Oschwald, Mike O'Regan, Tom Hukins, Omer Gazit, Evan Zacks, Paul Howarth, Sawyer X, Christian Walde, Dave Rolsky, Jakub Wilk, Roy Ivy III, Oliver Trosien, Glenn Fowler, Matt Creenan, Alex Balhatchet, Sebastian Paaske Tørholm, Stuart A Johnston, Dan Book, Steven Humphrey, James Raspass, Nick Tonkin, Harrison Katz, Douglas Sims, Mark Fowler, Alan Berndt, Neil Bowers, Sergey Romanov, Gabor Szabo, Graham Knop, Mike Eldridge, David Steinbrunner, Kirk Kimmel, Guillaume Aubert, Dave Cross, Anirvan Chatterjee, Todd Rinaldo, Graham Ollis, Karen Etheridge, Jonas Brømsø, Olaf Alders, Jim Keenan, Slaven Rezić, Szymon Nieznański.

AUTHOR

Jeffrey Ryan Thalhammer jeff@imaginative-software.com

COPYRIGHT

Copyright (c) 2005-2018 Imaginative Software Systems. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module.


Download Details:

Author: Perl-Critic
Source Code: https://github.com/Perl-Critic/Perl-Critic

License: View license

#perl 

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Samanta  Moore

Samanta Moore

1621137960

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review

How LogRocket Helps Codeverse Teaching Kids to Code

To help marketing teams write better content for search, they had the goal of maximizing the value that customers obtained from Topic.

#code #teaching kids to code