mardi 2 mars 2021

Rails - Controller DRY - Generic way of doing common filtering/sorting/pagination

Developing a new API, I noticed I will be repeating the same code across multiple indexes, Trying to avoid this, but not sure on the best method?

current scenario:

books_controller

        def index
          books = Book.filtered(query_params).sorted(sorting_params)
          .page(pagination_params[:page])
          .per(pagination_params[:per_page])
          #.includes(:author) // placeholder for dynamic includable associations

          json_response(BooksSerializer.new(books).as_json)
        end

Initial Idea I had, was creating ResourcesService, that would receive a model, for example Book class, and from there apply the methods (filtered, sorted..pagination) and return an ActiveRecord_Relation object to be serialized and returned.

Not sure on how to write it though (as a PORO or Module)

Any tips, on how to make this DRY and reusable across controllers?

Archieving something like, to reproduce on other controllers:

books = ResourceService.new(Book, query_params, sorting_params, pagination_params, includables)

WCAG guideline: 2.1.1 Keyboard

I have a Q on the wcag point 2.1.1 . In my application, I have a confirmation modal for "delete" action. So user click on "Delete" button and then "Are you sure " modal appears. In this modal, I have 2 buttons "Confirm" & "Cancel". Confirm is on the right, Cancel on the left. Which button should get focus on first?
I think as the guideline talks about meaningful sequences for a user, it should be Delete. Here the user intention is to confirm the action, so DELETE should have focus first.
Want to hear expert opinion. Thanks in advance

Can someone please answer the given scenarios? I've been trying to understand but got completely stuck

Consider each of the scenarios below and identify the design pattern which is most directly addresses the problem described. Briefly explain your reasoning.

You’ve developed a new implementation of the List interface and you’d like to test the behavior of your new data structure. You’ve written an algorithm to perform your speed tests, but the algorithm needs to make a great many instances of your list class. You want to test the performance of your list against the performance of ArrayList and LinkedList, but you don’t want to have to write your algorithm three times in order for it to be able to create the right kind of list to test.

You’ve completed a compiler for a new language! There are many parts to your compilation process: parsing, transformation, assembly code generation, and so forth. You’d like to allow other programmers to use an interface to compile their code without resorting to system calls or other command-line invocations – your compiler can just run in their processes – but you don’t want those users to have to know how to bring all of the steps of compilation together in order to use your compiler.

Role-based PHP Pattern

I'm building a simple booking system in Laravel which is used by both admins and normal users.

In my BookingController.php is have an index method to fetch all bookings.

public function index(Request $request): Response
    {
        $limit = ($request->has('limit')) ? $request->get('limit') : 20;

        $bookings = $this->booking
            ->pushCriteria(new BelongsToTeam())
            ->pushCriteria(new RequestWith())
            ->pushCriteria(new ModelFilter())
            ->orderBy('date')
            ->paginate($limit);

        return Inertia::render('Bookings/Index', [
            'filteredDate' => ($request->date && $request->date != '') ? $request->date : Carbon::now()->format('Y-m-d'),
            'filteredCalendar' => ($request->calendar && $request->calendar != '') ? $request->calendar : '',
            'bookings' => new BookingCollection($bookings)
        ]);
    }

The important bit here is

->pushCriteria(new BelongsToTeam())

This bit of code works fine for an admin when we want to return all the bookings that belong to this users team. I do, however, also want to use this controller method for normal users logging in to fetch all the bookings that belong to this user. This would obviously alter the database query I write to fetch the bookings based on the role that the logged in user has.

My question is, what pattern can I use to ensure that I avoid writing unnecessary if statements to determine how I fetch my bookings from the database?

lundi 1 mars 2021

Object oriented design - Library management system

I'm working on the class diagram for library management system and need help in defining the relationships between the following classes - person, member, librarian and account.

In my solution, I kept it as: Person has an Account instance Member and Librarian extends Person

But, when I referred to other solutions available on internet and famous interview preparing courses, it is modelled as follows: Account has a Person instance Member and Librarian extends Account

Can you please help with what advantage does the second one gives over first? What should be the correct way to go forward?

Returning an initialized structure from local scope unexpectedly works in C11

In our code base, I encountered some C code that I am not able to understand why it works.

Pretty sure implements some pattern found on the internet. Ideally this code should emulate some object-oriented pattern from C++, and it is used to create queues.

Here is (part of) the code for the declaration (.h) of the queue module:

struct Queue_t
{
  uint8_t         Queue[MAX_QUEUE_SIZE];
  uint32_t        Head;
  uint32_t        Tail;
  uint16_t        Counter;
  Queue_return_t  (*Push)(struct Queue_t * Queue, uint8_t * NewElement, uint16_t ElementSize);
  Queue_return_t  (*Pop)(struct Queue_t * Queue, Queue_Element_t *RetElement);
  Queue_return_t  (*Flush)(struct Queue_t * Queue);
};

extern const struct QueueClass {
        struct Queue_t (*new)( void );
} Queue_t;

struct Queue_t new( void );

Here is (part of) the code for the implementation (.c) of the queue module:

struct Queue_t new( void )
{
  struct Queue_t NewQueue;

[...]
  NewQueue.Push = &QueueManager_Push;
  NewQueue.Pop = &QueueManager_Pop;
  NewQueue.Flush = &QueueManager_Flush;
  return NewQueue;
}

const struct QueueClass Queue_t={.new=&new};

then the usage in the code is the following:

struct Queue_t Output_Queue;
Output_Queue = Queue_t.new();
[...]
RetQueue =  Output_Queue.Pop(&Output_Queue,Output_Queue_elem);

Now, we switched to a more straightforward queue implementation. Still I am not able to grasp what is going on in this code.

As stated in the title, my problem is in the "new" function, where a struct Queue_t is declared in a local scope and then returned.

As further information, in the project that used this "queue" module there was no dynamic memory allocation, hence no heap, free or malloc.

Everything worked really smooth, I would expect the code to crash as soon as the stack for the referenced object is freed and the pointer to the structure is accessed.

Also, the compiler used was IAR and is not complaining (this code was used on a uC).

Maybe the const qualifier is involved?

Any hint on what is going on?

Software Architecture: Leaflet based package for any web framework (jQuery, React, Angular, etc.)

I have built a package based on leaflet, which contains moving markers (divIcons) and controls via jQuery. There are several exported functions to manipulate these markers (divIcons) using jQuery within these functions.

I'm now considering to integrate this package into jQuery, ReactNative and Angular based apps. Of course, I could keep the internal logic with jQuery and use the exported functions to interact with the map, but I'm wondering if there's a universal approach?

The only thing I could think of is using VanillaJS DOM manipulation. Any other ideas or lightweight libraries?

Thank you!