投稿時間:2023-01-13 06:21:18 RSSフィード2023-01-13 06:00 分まとめ(21件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
海外TECH Ars Technica Biden taking “absolutely wrong approach” to crack down on Big Tech, critics say https://arstechnica.com/?p=1909620 approach 2023-01-12 20:16:02
海外TECH MakeUseOf What Is a File Systems Table (fstab) on Linux and Why Is It Important? https://www.makeuseof.com/what-is-fstab-file-systems-table-linux/ systems 2023-01-12 20:30:17
海外TECH MakeUseOf How to Send Handwritten Messages on Your iPhone https://www.makeuseof.com/how-to-send-handwritten-messages-on-iphone/ handwritten 2023-01-12 20:15:16
海外TECH DEV Community Assembly For JavaScript Developers https://dev.to/____marcell/assembly-for-javascript-developers-p0h Assembly For JavaScript DevelopersWhy Should You Care Lines Of Code vs InstructionsAssembly Is Not A Language Differences Between HardwareWhy am I writing This Fibonacci CodeNaming the conceptsSomething Like A FunctionPassing Data To The FunctionCreating ScopeThe Stack Another Way Of Saving Data Using The Stack To Save Data And Create ScopeReturning Data To The CallerIf Statements In AssemblyConditional LogicRecursionPutting Everything TogetherFinal CodeIO In AssemblyFinal Code With IOHow To Debug AssemblyCodeIf you only code in high level languages and have no idea what your computer does with your code this post is for you no previous knowledge of assembly is required just basic knowledge of any popular language if you can read and understand the following JavaScript code you re good to go function fib n if n lt return n return fib n fib n fib return fib returns fib also returns fib returns and so on We re gonna implement this in assembly breaking down each JavaScript concept and implementing the same concept in assembly The main problem that I ve had learning assembly is that is boring and the reason why is boring is because you have to understand a lot to do a little and the thing that you end up doing is not that interesting so I decided to write this post that tries a different approach Why Should You Care If you re a JavaScript developer you not going to use assembly in your daily routine and knowing assembly is not gonna make you a better JavaScript developer in any meaningful way so why should you care Well Knowing assembly will increase your understanding of computing and make you more interested in it it ll open doors in other areas that might grab your interest and the most important part it ll build your narrative about programming you need to be able to tell a history with the knowledge that you have to be interested in it learning assembly will increase your context appreciation and understanding of the whole field if you feel like you re repeating yourself learning the same concepts over and over just with different names said by different people maybe it s time to learn something new to expand your view and reignite your interest in programming at the end of the day you can t be good at something that you don t enjoy and have no interested in so allow yourself the opportunity of sparkling your interested once more if you don t know C you can t fully appretiate javascript if you don t know assembly you can t fully appretiate C it s important to know where the things that you use come from to understand why they exist to build meaning Knowing how to do something is not the same as understanding it you need a lot of context to understand something you need to connect the dots the more context you have the easier it s for you to understand other things in the same area and the deeper is your understanding you can explain the why why something was built the way it was and why it s not a good idea to do it differently what are the downside of a solution you level of enjoyment and interest in the field also grows because your mind have a lot more room to wonder in that particular field so let s get to it Lines Of Code vs InstructionsYour computer can t execute the code that you write let x your computer has no idea what the previous line of code means and what do to with it this line of code needs to be translated to instruction that your CPU can actually execute the code that you write is called subject code or source code this code needs to be translated to object code real instructions that your CPU can execute one line of code in a high level language gets translated to multiple instructions that a CPU can actually execute computers are super dumb they do not understand any of these high level concepts they can only do very simple things like Move values to different places in memory Add and subtract numbers Jump to different instructions And that s pretty much it the hardware on your computer is very limited don t get me wrong it s amazing that we have circuitry that can actually do these things but there s a chasm between the concepts in a high level language and what the hardware can actually do it s the job of the person designing the language to bridge that chasm and implement these high level concepts like functions recursion and scope using only these very simple tools and that s what we gonna do in this post we gonna reverse engineer a solution in a high level language JavaScript to a low level language assembly Assembly Is Not A Language Assembly is not a language assembly is a family of languages just like LISP is also a family of languages if all the code that you write maps directly to a instruction that a machine can do this language can be called an assembly language the name assembly comes from the fact that what the machine is executing is not exactly the instruction the machine can execute multiple instructions at once and these instructions are assembled in to binary the following table illustrates how that happensSo multiple assembly instructions gets assembled to one or bit chunk of data that a computer can execute for example the jump instruction in assembly might be represented by the last bits in these chunks the first bits represents the move instructions and so on you got the idea you don t need to understand any of this to write assembly the assembler is smart enough to do it An assembly language is made for a specific CPU since different CPU can do different things and execute different instructions the difference between what a CPU can do makes the CPU more suited for different tasks if you need to do a lot of multiplication using a CPU that can do multiplication on hardware will be a lot better than one that can only add Differences Between HardwareDepending on your task difference instruction will be more important and that dictates what instructions will be implemented on hardware creating chips that can execute complex instructions is expensive but also make the execution of those instructions much faster that s why people use GPU s for AI mining crypto and games GPU s have expensive instructions implemented on hardware so things that would take a lot of instructions in a regular CPU can be done with a single GPU instruction GPU makers release documents with these instructions so assembly creators can create a assembly language that maps to these instructions or even higher level languages like shader languages for example the following is a pdf document with the instructions for the AMD R family if you re curious Why am I writing This Most of the tutorials online focus on teaching assembly bottom up show the instruction tell what the instruction does then show another instruction and so on but I think this way of teaching assembly is much more complicated than it needs to be assembly is not like other high level languages so knowing what a specific instruction do has no value for a python or Javascript developer because that instruction doesn t map to anything that you already know saying that MOV moves numbers to registers has no meaning to a high level language developer the first thing that he s going to think is what is a register and why would I move numbers to it So instead of doing this we re going to implement a function that returns the value of a number in a fibonacci sequence first we re going to write the code in Javascript then we re going to translate the code to assembly and conceptually map each part to the high level code Fibonacci CodeEach number in the Fibonacci sequence is the sum of the previous two values expect for the first two values which are and Let s see the javaScript implementation again function fib n if n lt return n return fib n fib n fib return fib returns fib also returns fib returns and so on Ok now let s talk about the high level concepts used in this implementation the idea is the following name the conceptsfind similar concepts in assemblytranslate the concepts to assembly Naming the conceptsThe first concept is functions function fib is a function in JavaScript we can think about what properties does a function have let s number the properties and think about them A function can be called from anywhere in the code You can pass data to the function The function have a scope The function can return data to the callercode execution resumes right after the function call after the function returns now we think about something in assembly that is conceptually similar something that can emulate what we want to do Something Like A FunctionThere are no functions in assembly but we have something close to it called procedures if you think about a function in another way a function is a jump in the program execution in our example the first line executed was fib this line prompt a jump in the execution to line function fib n in assembly you can name a specific line and tell the program to jump to that line and keep executing the code global start start call Proc retProc push retCode execution starts at start which is a procedure the line at start and all following lines will be executed unless we have something to change the next line to be executed in this case we call another procedure called Proc there s nothing special about the name it s just a label that s going to be replaced by the address in memory of the next instruction to be executed When we run call Proc code execution will jump to line ok so now we have a way of jumping between different parts of the code the first property that we want let s look at what is happening Above is the code that we just wrote being executed the first column is the memory address of that line of code code execution start at the first address the address is incremented to the next address and the code on that address is executed except when we use call call changes the value of the next line to be executed so code execution jumps to the instruction push the next line is ret which works like return but can not return values after that code execution resumes after the call instruction ok that s one part of the puzzle now we have a way of changing the execution flow case is complete Passing Data To The FunctionNow that we have something that we can call like a function how do we pass data to it most of what a higher level language do is managing memory the biggest benefit of using lanuguages like javascript and python is that you don t need to manage memory yourself most runtime errors are caused by bad memory allocation either by the language OS or the developer in most computers and OSs you have at least ways of saving temporary data that is being used in a process you have registers the stack and the heap registers are the easiest one to understand and use in assembly an register is a integrated circuit that can save bits it s hardware and you have a limited number of those in your computers a lot of register are used for other tasks by the CPU so it s not safe to use them that s why you hear people talking about general purpose registers these are the registers that re safe to be used by your running program the following image is a list of almost all the registers in an modern computer Since a register is hardware registers are global even between different programs if you change the value of a register in one part of your program and then call another library or procedure that reads or change this registers you gonna affect your program or the library that you re using so it s always a good idea to keep the number of registers that you use to a minimum just like we do with global variables The road to programming hell is paved with global variables How can we save something in a register That s when the MOV instruction comes in you can move a value to a register MOV RAX here we re moving the value to the RAX register and we can do that to save a value and then read it in another part of the program which is similar to passing data to a function we can do something like this global start start mov rax call Procedure retProcedure add rax now the value on rax will be retIn the snippet above we save the value on rax call the procedure then read the value from that variable and do something with it simulating passing values to a function so is also done Creating ScopeAnother useful function property is scopes variables created in a function only exist on that scope and if you recursively call that function passing new values updating these values won t affect other scopes this is a key property of functions and is the main reason why they re so useful function fib x fib fib So can we do something like this in assembly How can we simulate scope As you might have guessed we don t have the concept of a scope in modern CPUs so we have to simulate one if you re paying attention the first thing that you would think about would be to use the registers to save and load different scopes depending on what you re executing at that moment the problem is that we have a very limited number of registers so if we do that we re going to run out of registers to save values pretty fast they re global as well so abusing registers is not a good idea OK so the other general options to save things are the stack and the heap let s talk about the stack The Stack Another Way Of Saving Data Another way of saving data is the stack the beautiful thing about the stack is it s simplicity when you run your program the OS reserves some memory for the program to run and sets the address of the beginning of that memory to a register rsp when you push a value to the stack it saves this value to the current memory address saved on rsp and increases the memory address to the next one in the stack and saves it on rsp again when you pop a value it saves the value on whatever register you tell it to and decreases the rsp memory address number again We could do all of that ourselves but x comes with two instructions that already do all of that for us push and pop let s see that happening step by step This is the code that we gonna runglobal start start push push pop rax pop rbx retWe can push a value to the stack using push push will push the value to the stack is in hexadecimalAnd this is the stack before running anythingThe first column is the memory addresses and each line is the value in memory when we run push the stack changesNow we can see our or in hexadecimal there if we run the next instruct push again is added to the stackAs you can see we add to the stack in chunks of bits because my computer is bits if you re using a bit computer you would see a word half the size as the one we re seeing here you can read more about what word means here here but basically a word is the size of the data that makes sense to work on a given the computer architecture you can work with bit registers in a bit computer but that s going to make your life harder in most cases let s keep executing our code to see what happens when we pop a value from the stack pop rax remove the value from the stack and save that value on a register rax in this case that s one of the reasons why the default size of the word matters because if we tried to save a bit value in a bit register bad things would happen as you can imagine rax is a bit register so we can safely do that let s see what happens to the stack after we pop that value Now we only have one again and the value of the registers that points to the top of the stack RSP was decreased if we ran the next pop we gonna remove the next value from the stack and the stack will be in the same state as it was before we started the program RSP will point to the beginning of the stack the OS allocates memory for the program and decides which address the stacks starts on Using The Stack To Save Data And Create ScopeNow that we know how the stack works we can use the stack to save and retrieve all register values before calling another procedure by doing that we can create scope between the different procedure calls let s see the easiest possible example of that in practice start mov rax the value that we pass to Procedure call Procedure retProcedure push rax saves rax on the stack call ChangeParam call a procedure that changes rax pop rax restore rax original value from the stack retChangeParam add rax now the value on rax is retSaving the values that we re working on in the stack and restoring them creates scope in the procedure we could have done the same thing on ChangeParam that s usually the way that we do when we call external libraries we need to restore the values before calling them great now we have a way of creating scope is done Returning Data To The CallerWell this one is pretty easy since everything is global in assembly the caller just needs to read the value in the right place after the call so if inside the procedure we save the result of the procedure in the RBX register we just need to read the value from that register after the procedure start call Procedure mov rax rbx now rbx has the result of proc retProcedure mov rbx retAnd with that we re done now let s analyze the next line of javascript code and do the same thing that we done for the function If Statements In Assemblyif n lt This is the next executed JavaScript as you might imagined by now Assembly x doesn t have if statements either The main function that we want to simulate is Compare two values and based on the result of the comparison jump to different places Conditional LogicThis one is pretty straight forward we have CMP in assembly the way that it works is pretty simple we compare two values then we use a conditional jump to jump in specific cases for example we could compare the value on RAX with then do a conditional jump if they re equal start cmp rax je ProcProc push That s pretty much it not much to talk about here we have conditional jumps for each comparison greater than JG less than JL equal JE and for some other special cases RecursionThe next line is return n we already implemented the return logic we just need to save the value in the register and use ret to return from a procedure and for n we just need to use decrement dec on the register holding the value of n the last line of javascript is return fib n fib n and we also implemented everything that that is to know about this one the main thing about this line is the fact that is recursive and we already implemented the idea of a function with scope so we only need to call the procedure save the data on the stack and the rest that we did to simulate a function call Now we can put everything together and implement the solution Putting Everything TogetherLet s go line by lineFunction definitionfunction fib n Procedure definitionFib If statementif n lt Compare and jumprax holds the parameter passed to the functioncmp rax jl L jump to L if rax is less than Inside the if blockreturn n We jump to another part of the code decrement the register and save the value to another register before returning since this is the last case we don t need to push rax to the stack again jumps works in a different way than procedure calls when you call a procedure ret gonna return you in the line that you called that procedure when you jump it can look like a procedure but it isn t the code belongs to the procedure where you used the jump so ret is going to return from that procedure it works just like a if statement in this case L dec rax mov rbx rax retreturn fib n fib n This one is complicatedpush rax saves the value of rax rax is n in this contextdec rax decrements rax call Fib call procedure now with the modified rax valuepop rax pops the original value of rax from the stackpush rbx push the result from the previous Fib call dec rax decrements rax two times n dec raxcall Fib calls procedure now with the modified rax valuepop rcx pop the result from the first Fib calladd rbx rcx add the result from the first Fib call with the second oneretAs you can see simulating scope is the trickiest part but it s not that hard if you take some time to think about it we re just using the stack to save stuff that we want to use later and not change the things that we re working right now the stack is used a lot in this manner you don t want to use right now but needs this value later put it on the stack Final Codeglobal start start mov rax call Fib Some boilerplate code to return control to the OS mov eax Code for Exit Syscall mov ebx Return a code of zero int H Make kernel call retFib cmp rax jl L push rax dec rax call Fib pop rax push rbx dec rax dec rax call Fib pop rcx add rbx rcx retL dec rax mov rbx rax retin the case above is the parameter that the fib function receives so the returned value should be is the fifth element in the fibonacci sequence if we ran our code and inspects the value of rbx at the end of the execution we get IO In AssemblyOne thing that is clearly missing is the ability to pass arguments to our program and to print out the results I didn t touch on this before because is not really assembly but we can do that to make our program more useful the way that something like print hello world works is by calling a function of the Kernel that knows how to print things on the screen we also need to read the arguments passed to the function transform the numbers in to characters and the characters in to numbers by offsetting the values in the ascii table I m not gonna explain this here because the post is already pretty big the following is the code with IO you can pass the index in the fibonacci that you want and the code returns the value in the sequence Final Code With IO macro ExitProg mov eax Code for Exit Syscall mov ebx Return a code of zero int H Make kernel call endmacrosection data newline db section bss printSpace resb digitSpace resb digitSpacePos resb section textglobal start start mov rdi qword rsp Get the third item in the stack which is the first argument passed to the program movzx rax byte rdi Get the first character sub rax Convert from ASCII to decimal call Fib after call Fib rbx has the result mov rax rbx moves the result to rax call printRAX call procedure to print the result mov rax newline move new line to rax call print prints the new line ExitProgFib cmp rax jl L push rax dec rax call Fib pop rax push rbx dec rax dec rax call Fib pop rcx add rbx rcx retL dec rax mov rbx rax retprint mov printSpace rax call printLoop retprintLoop mov cl rax cmp cl je endPrintLoop inc rbx inc rax jmp printLoopendPrintLoop mov rax mov rdi mov rsi printSpace mov rdx rbx syscall retprintRAX mov rcx digitSpace mov digitSpacePos rcxprintRAXLoop mov rdx mov rbx div rbx push rax add rdx mov rcx digitSpacePos mov rcx dl inc rcx mov digitSpacePos rcx pop rax cmp rax jne printRAXLoopprintRAXLoop mov rcx digitSpacePos mov rax mov rdi mov rsi rcx mov rdx syscall mov rcx digitSpacePos dec rcx mov digitSpacePos rcx cmp rcx digitSpace jge printRAXLoop ret How To Debug AssemblyYou can use gdb to debug Assembly but you need to configure it properly this is the configuration that I use besides that to start debugging rungdb fibonacciif you needs to pass parameters to the programgdb args fibonacci after that you can break on the start procedureb startrun the programrunThen you can use nexti to go to the next instruction and stepi to step inside a procedure i r lt register name gt shows the value of a register e g i r raxWe can print address values of registers and symbols with x x rsp to print in hexadecimal and x d to print as a decimal value CodeAll code is available here 2023-01-12 20:56:31
海外TECH DEV Community How To Create A Toast Notification in Javascript https://dev.to/arafat4693/how-to-create-a-toast-notification-in-javascript-261d How To Create A Toast Notification in Javascript What is this article about A toast notification is a simple way to provide essential information to the user It is a small message that appears on the screen for a short period In this article you ll learn how to build a toast notification using pure HTML CSS and JS No library is included Steps to followCreate a index html fileCreate a style css fileCreate a script js fileTo get started add the following code to your HTML file This HTML code will create five buttons to click for the toast notification Afterward we will dynamically add a toast li element in the notification ul using JavaScript lt DOCTYPE html gt lt html lang en dir ltr gt lt head gt lt meta charset utf gt lt title gt Toast Notification In Javascript lt title gt lt link rel stylesheet href style css gt lt meta name viewport content width device width initial scale gt lt Font Awesome icons gt lt link rel stylesheet href gt lt script src script js defer gt lt script gt lt head gt lt body gt lt ul class notifications gt lt ul gt lt div class buttons gt lt button class btn id error gt Error lt button gt lt button class btn id warning gt Warning lt button gt lt button class btn id info gt Info lt button gt lt button class btn id success gt Success lt button gt lt button class btn id random gt Random lt button gt lt div gt lt body gt lt html gt Following add the following CSS code to your CSS file These codes are for styling the toast notification Feel free to customize the design to suit your tastes Import Google font Poppins import url wght amp display swap margin padding box sizing border box font family Poppins sans serif root dark fad light ffffff success abf error edc warning ebdc info db random ebff body display flex align items center justify content center min height vh background var dark notifications position fixed top px right px notifications where toast column display flex align items center notifications toast width px position relative overflow hidden list style none border radius px padding px px margin bottom px background var light justify content space between animation show toast s ease forwards keyframes show toast transform translateX transform translateX transform translateX transform translateX px notifications toast hide animation hide toast s ease forwards keyframes hide toast transform translateX px transform translateX transform translateX transform translateX calc px toast before position absolute content height px width bottom px left px animation progress s linear forwards keyframes progress width toast success before btn success background var success toast error before btn error background var error toast warning before btn warning background var warning toast info before btn info background var info toast random before btn random background var random toast column i font size rem toast success column i color var success toast error column i color var error toast warning column i color var warning toast info column i color var info toast random column i color var random toast column span font size rem margin left px toast i last child color aebd cursor pointer toast i last child hover color var dark buttons btn border none outline none cursor pointer margin px color var light font size rem padding px px border radius px media screen and max width px notifications width notifications toast width font size rem margin left px buttons btn margin px font size rem padding px px Ultimately paste the following javascript code to your script js file const notifications document querySelector notifications buttons document querySelectorAll buttons btn const toastDetails timer success icon fa circle check text Hello World This is a success toast error icon fa circle xmark text Hello World This is an error toast warning icon fa triangle exclamation text Hello World This is a warning toast info icon fa circle info text Hello World This is an information toast random icon fa solid fa star text Hello World This is a random toast const removeToast toast gt toast classList add hide if toast timeoutId clearTimeout toast timeoutId setTimeout gt toast remove const createToast id gt const icon text toastDetails id const toast document createElement li toast className toast id toast innerHTML lt div class column gt lt i class fa solid icon gt lt i gt lt span gt text lt span gt lt div gt lt i class fa solid fa xmark onclick removeToast this parentElement gt lt i gt notifications appendChild toast toast timeoutId setTimeout gt removeToast toast toastDetails timer buttons forEach btn gt btn addEventListener click gt createToast btn id This Javascript code first defines an object called toastDetails that contains details for different toasts including a timer for how long the toast should be displayed and information for each type of toast such as an icon and text The code then defines two functions removeToast and createToast The removeToast function is used to remove a toast from the DOM by adding a hide class to the toast element clearing any timeout that was set to release the toast and then removing the element from the DOM after a delay of ms The createToast function is used to create a new toast element setting its classes and innerHTML based on the type of toast specified by the id passed as an argument and appending it to the notifications element Finally the code adds a click event listener to each button so that when a button is clicked it will call the createToast function and pass the id of the clicked button as an argument ConclusionThat s all Congratulations You successfully created your Toast Notification in HTML CSS and JavaScript If you encounter any problems or your code is not working as expected feel free to ask in the comment section 2023-01-12 20:53:53
海外TECH DEV Community Llamando a un flujo de Power Automate desde .NET https://dev.to/esdanielgomez/llamando-a-un-flujo-de-power-automate-desde-net-4o7c Llamando a un flujo de Power Automate desde NETEn este tutorial aprenderemos a llamar un flujo de Power Automate desde NET por medio de un HTTP post Para este objetivo utilizaremos un ejemplo para enviar un correo electrónico Este es el flujo creado en Power Automate Aquípodemos ver el proceso para crearlo Implementación en NETEn primera instancia debemos hacer referencia al endpoint de nuestro flujo de Power Automate private string uri HTTP POST URL Luego podemos definir un método en un servicio por ejemplo para poder llamarlo desde alguna parte de nuestra aplicación y este recibirácomo parámetros el username toAddress y el emailSubject La idea con este método es poder preparar la solicitud para el HTTP post y que el flujo de Power Automate se pueda desencadenar public async Task SendEmailAsync string username string toAddress string emailSubject try HttpClient client new HttpClient client BaseAddress new Uri uri client DefaultRequestHeaders Accept Clear client DefaultRequestHeaders Accept Add new MediaTypeWithQualityHeaderValue application json HttpRequestMessage request new HttpRequestMessage HttpMethod Post client BaseAddress var body emailAddress toAddress emailSubject emailSubject userName username var content new StringContent body Encoding UTF application json request Content content var response await MakeRequestAsync request client Console WriteLine response catch Exception e Console WriteLine e Message throw new Exception Finalmente podemos contar con un método adicional para poder realizar el HTTP post request de acuerdo con la solicitud establecida previamente public async Task lt string gt MakeRequestAsync HttpRequestMessage getRequest HttpClient client var response await client SendAsync getRequest ConfigureAwait false var responseString string Empty try response EnsureSuccessStatusCode responseString await response Content ReadAsStringAsync ConfigureAwait false catch HttpRequestException empty responseString return responseString Pruebas con este código en una aplicación web con ASP NET Para realizar las pruebas vamos a ver un ejemplo en una aplicación web desde ASP NET que llama a este servicio de Power Automate implementado para cuando un usuario es agregado desde un formulario y notificado por correo electrónico con este flujo await new PowerAutomateService SendEmailAsync student FirstName student Email Greetings from ASP NET DotVVM web application Gracias Espero que te haya gustado el artículo Si tienes alguna pregunta o idea en mente seráun gusto poder estar en comunicación e intercambiar conocimientos entre sí Nos vemos en Twitter esDanielGomez com 2023-01-12 20:04:28
海外TECH DEV Community Rails Hotwire: mastering techniques for streamlining inline editing in your user interface https://dev.to/ahmednadar/rails-hotwire-mastering-techniques-for-streamlining-inline-editing-in-your-user-interface-1h5m Rails Hotwire mastering techniques for streamlining inline editing in your user interfaceOriginally posted on ahmednadar comRecently the inline editing capabilities demand has increased a lot It allows users to edit certain fields in a form directly on the form page without navigating to a separate edit page No refresh nor reload page is needed And why not since it enhances user experience and saves time In the Rails world thanks to Hotwire s stack inline editing is fun and a simple task In this post you will know how to implement inline editing in a Rails application using Hotwire Turbo scenarioA client asks OR your application requires you to create a Contact object with first name last name and email attributes Users are allowed to inline edit first name and last name attributes only without a page reload refresh First we scaffold the Contact object like so rails g scaffold contacts first name last name email In the Contact model create an EDITABLE ATTRIBUTES constant that lists the attributes to be edited inline first name and last name While you are here add a validation that requires the first name and last name attributes to be present app models contact rb class Contact lt ApplicationRecord EDITABLE ATTRIBUTES first name last name freeze validates first name last name presence true end Scaffold kindly enough generated contact html erb partial to render a single contact app views contacts contact html erb lt div id lt dom id contact gt gt lt Contact EDITABLE ATTRIBUTES each do attribute gt lt render editable attribute contact contact attribute attribute gt lt end gt lt div gt Above instead of listing each attribute individually loop through EDITABLE ATTRIBUTES and render editable attribute html erb partial to edit each attribute app views contacts editable attribute html erb lt turbo frame tag attribute do gt lt link to contact attribute presence Edit field edit contact attribute attribute gt lt end gt Notice the use the turbo frame tag helper here to wrap each attribute with the id attribute which matches the same id within the editable attribute form html erb partial below and updates it using TurboStreams app views contacts editable attribute form html erb lt turbo frame tag params attribute do gt lt form with model contact url contact attribute attribute method patch do form gt lt if contact errors any gt lt div style color red gt lt ul gt lt contact errors each do error gt lt li gt lt error full message gt lt li gt lt end gt lt ul gt lt div gt lt end gt lt form text field attribute onchange this form requestSubmit gt lt form submit gt lt end gt lt end gt Above partial renders a form for editing a single attribute It uses the form with helper to create a form that submits a patch request to update contact Notice it is using the same id attribute that matches the previous partial The form includes a text field field for a dynamically selected attribute matching name as params attribute Each field has an onchange event that submits the form when the value of the field changes Lastly update the edit html erb template to render the edit page for contact If the attribute parameter is present in the request the template renders the ‌ editable attribute form html erb partial to allow the user to edit a single attribute inline If the attribute parameter is not present the template renders the form partial to allow the user to edit all attributes of the contact object at once Rails form that you are familiar with app views contacts edit html erb lt if params attribute present gt lt render editable attribute form contact contact gt lt else gt lt render form contact contact gt lt end gt As you see Rails with Hotwire stack offers the amazing ability for developers to do a fantastic job with little effort and no relying on external libraries RefactorAs all developers do we like to write less and reduce DRY You can simplify and refactor your code as follow Extracted the logic for rendering editable attribute html erb and editable attribute form HTML erb partials code into a new helper module EditableAttributesHelper By doing so you need to update both contact html erb partial and edit html erb template and call the new helper instead app views contacts contact html erb lt div id lt dom id contact gt gt lt Contact EDITABLE ATTRIBUTES each do attribute gt lt turbo frame tag attribute do gt lt render editable attribute contact attribute gt lt end gt lt end gt lt div gt Above we call the render editable attribute method and pass in the contact object and the attribute as arguments app views contacts edit html erb lt if params attribute present gt lt turbo frame tag params attribute do gt lt render editable attribute form contact params attribute gt lt end gt lt else gt lt render form contact contact gt lt end gt And in the edit html erb template we call the render editable attribute form method and pass in the contact object and the params attribute as arguments Let s check your new helper module app helpers editable attributes helper rb module EditableAttributesHelper def render editable attribute contact attribute content tag p do concat link to contact attribute presence Edit edit contact attribute attribute end end def render editable attribute form contact attribute form with model contact url contact attribute attribute method patch do form content if contact errors any content lt lt content tag div class flex text red flex col bg pink do content tag h pluralize contact errors count error prohibited this contact from being saved content tag ul do contact errors each do error concat content tag li error full message end end end end content lt lt content tag div do content lt lt form text field attribute onchange this form requestSubmit autofocus true content lt lt form submit Update attribute humanize end content join html safe end end end The render editable attribute method renders a link to the edit action with the attribute parameter set to the current attribute The render inline attribute form method renders a div element with a form containing a text field tag for the selected attribute If there are any errors they are displayed in a div element with TailwindCSS styles Nothing drastically changed from previous partials By extracting the logic for rendering both partials into a helper class we have made the code more reusable and easier to maintain We can now use the render editable attribute and render editable attribute form methods in any view in our application to render editable inline attributes and forms Notice content join html safe It takes an array of strings content and joins them into a single string by calling join method on the array contnet Then it marks the resulting string as safe for output in an HTML context by calling the html safe method on it The html safe method tells Rails to not escape the string when it s output in an HTML template which is typically used when you want to output HTML tags Final thoughtsImplementing inline editing is a powerful feature that can improve the user experience of your application by allowing users to edit data directly on the page without having to reload the page or navigate to a separate page Thanks to Rails Hotwire Turbo made the process of doing so easy fun and straightforward And as usual Happy Coding 2023-01-12 20:01:02
海外TECH Engadget Russia will send a 'rescue' spacecraft to the ISS following leak https://www.engadget.com/russia-soyuz-capsule-rescue-mission-iss-205343374.html?src=rss Russia will send a x rescue x spacecraft to the ISS following leakRussia is prepping a rescue mission following a coolant leak on a Soyuz capsule docked with the International Space Station NASA said in a media briefing that Russia s Roscosmos agency will send an empty Soyuz to the station on February th as a replacement for the damaged spacecraft The vehicle was originally supposed to launch in March The leaking capsule is expected to return to Earth without a crew sometime in March It will still carry experiments and other cargo Cosmonauts Dmitriy Petelin and Sergey Prokopyev as well as NASA astronaut Frank Rubio will now remain in orbit for several months longer rather than departing in March as planned The affected craft started spraying particles December th The ISS team quickly noticed that an external radiator cooling loop was to blame and investigators later determined that a micrometeoroid struck the radiator Roscosmos soon decided the Soyuz was too dangerous to use for a standard crew return Temperatures would have climbed past F on reentry threatening both occupants and computer equipment An in space repair would be impractical as the procedure would be too difficult according to the agency s Sergei Krikalev The ISS crew is still prepared to use the broken Soyuz to evacuate in an emergency However that s not ideal when three of the seven people aboard the ISS would likely have to accept elevated risks to come home A SpaceX Crew Dragon capsule is also docked but it normally only takes four occupants NASA s ISS program head Joel Montalbano said at the briefing that there had been talks with SpaceX to see if one of the Soyuz passengers could travel aboard the Crew Dragon if necessary Relations between NASA and Roscomos are strained following Russia s invasion of Ukraine Russia said last summer that it would leave the ISS after to work on its own space station and the US has been preparing for a possible Russian withdrawal since However the capsule leak has effectively forced the two to work closely together ーif only briefly 2023-01-12 20:53:43
海外TECH Engadget Congress blocks purchase of more Microsoft combat goggles https://www.engadget.com/microsoft-hololens-army-combat-goggles-congress-block-202637552.html?src=rss Congress blocks purchase of more Microsoft combat gogglesThe US government has reportedly passed on buying more HoloLens based AR combat goggles from Microsoft after discovering the current version has some kinks to work out according to Bloomberg So instead of ordering more of the current model the government approved million for Microsoft to develop a new version The updated combat goggles will address test results from last year when soldiers wore the current version during three hour scenarios simulating combat conditions The results showed that the soldiers suffered “headaches eyestrain and nausea and that the system had too many “failures of essential functions In addition more than percent of soldiers who reported discomfort began experiencing it less than three hours into the hours test The Army had initially requested million to buy up to pairs of the goggles as part of the trillion government funding bill Instead Congress approved million from that sum to develop the new version The Army has already given Microsoft million to create a revised model and it still plans to spend up to billion over the next decade for as many as devices The Department of Defense contract has significantly boosted Microsoft s ability to profit from its AR device Before working with the DoD the company had marketed the headset for enterprise manufacturing training and other industrial purposes Although Microsoft has hinted at an eventual consumer version of HoloLens the company hasn t yet announced any specifics ーand its plans are hazier after the company has reportedly struggled to form a coherent strategy for its headset 2023-01-12 20:26:37
海外TECH Engadget Instacart will pay $5.25 million to settle a workers' benefit case https://www.engadget.com/instacart-workers-benefit-settlement-san-francisco-200117303.html?src=rss Instacart will pay million to settle a workers x benefit caseInstacart will pay workers million as part of a settlement after it allegedly failed to provide some benefits as The San Francisco Chronicle reports San Francisco accused the company of violating healthcare and paid sick leave ordinances The company which has not admitted to wrongdoing will pay an additional to cover the city s legal costs and pay for a settlement administrator to distribute the funds “Instacart has always properly classified shoppers as independent contractors giving them the ability to set their own schedule and earn on their own terms Instacart said in a statement “We remain committed to continuing to serve customers across San Francisco while also protecting access to the flexible earnings opportunities Instacart shoppers consistently say they want People who worked as independent contractors for Instacart in the city between February and December are eligible for payments based on how many hours they worked San Francisco estimates that between and people are affected by the settlement The city and Instacart previously reached a similar settlement that covered an earlier time period San Francisco has settled a benefits related case with DoorDash too After December th Instacart workers were subject to Proposition which afforded them some benefits without the company having to define them as employees An Alameda County Superior Court judge ruled in that the measure was unconstitutional but it remains in force while Instacart DoorDash Uber Lyft and other gig companies who bankrolled Prop appeal the decision Another suit ーfiled by San Francisco Los Angeles and San Diego ーclaims that Uber and Lyft drivers should have been classed as workers until Prop passed 2023-01-12 20:01:17
海外TECH CodeProject Latest Articles TuyaMusicSync https://www.codeproject.com/Articles/5351859/TuyaMusicSync unseen 2023-01-12 20:40:00
海外TECH CodeProject Latest Articles Angular Control to Process and Event Visualization https://www.codeproject.com/Tips/5350642/Angular-Control-to-Process-and-Event-Visualization displays 2023-01-12 20:20:00
ニュース BBC News - Home University staff plan 18 new days of strikes https://www.bbc.co.uk/news/education-64253904?at_medium=RSS&at_campaign=KARANGA college 2023-01-12 20:31:33
ニュース BBC News - Home UK falling behind in net zero race, review finds https://www.bbc.co.uk/news/uk-politics-64257057?at_medium=RSS&at_campaign=KARANGA approach 2023-01-12 20:26:51
ビジネス ダイヤモンド・オンライン - 新着記事 終身の「医療保障」に50~60代は要注意!保険料を一生払い続けられる?負担軽減の奥の手も - 「お金」大全 https://diamond.jp/articles/-/315629 医療保険 2023-01-13 05:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 23年の欧州経済はマイナス成長の可能性大、「内向き」ドイツがトラブルメーカーに - 総予測2023 https://diamond.jp/articles/-/314567 天然ガス 2023-01-13 05:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 フェリス・津田塾…【私立女子20大学】偏差値40年間の歴史、大妻・昭和女子は上昇基調 - 183大学1225学部 偏差値40年の歴史 https://diamond.jp/articles/-/315646 フェリス・津田塾…【私立女子大学】偏差値年間の歴史、大妻・昭和女子は上昇基調大学学部偏差値年の歴史各大学の偏差値に対する“記憶や“印象は、各世代で異なる。 2023-01-13 05:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 元外資コンサルの独学「読書の技法」、ビジネス書と教養書は読み方を変えろ! - 仕事に効く!独学バイブル https://diamond.jp/articles/-/315357 元外資コンサルの独学「読書の技法」、ビジネス書と教養書は読み方を変えろ仕事に効く独学バイブル現代は既存のビジネススキルがにわかに陳腐化し、すぐに新たなスキル習得を求められる大激変期です。 2023-01-13 05:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 個人投資家がプロに勝つための最強武器!「長期&分散」投資の極意 - 「お金」大全 https://diamond.jp/articles/-/315628 個人投資家 2023-01-13 05:05:00
ビジネス 東洋経済オンライン インバウンド蒸発から「復活の兆し」の売れた商品 免税購入の構成比が高い店舗で買われているもの | 消費・マーケティング | 東洋経済オンライン https://toyokeizai.net/articles/-/645290?utm_source=rss&utm_medium=http&utm_campaign=link_back 受け入れ 2023-01-13 05:40:00
ビジネス 東洋経済オンライン 空き家は「2023年」に売却したほうがいい理由3つ 「相続登記」の義務化が2024年に迫っている | 街・住まい | 東洋経済オンライン https://toyokeizai.net/articles/-/644183?utm_source=rss&utm_medium=http&utm_campaign=link_back 日本全国 2023-01-13 05:20:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)